KingOfHeart Posted December 10, 2008 Share Posted December 10, 2008 How would I search a string and if a value is too high, it would modify it to something else. Example: John had 3 apples, Peter had 20 apples, Ralf had 8 apples. If value is above 10, change it to a 10. Guessing I need str_replace, but not sure how in this case. Quote Link to comment https://forums.phpfreaks.com/topic/136306-modifying-a-value/ Share on other sites More sharing options...
.josh Posted December 10, 2008 Share Posted December 10, 2008 $string = "John had 3 apples, 100 Peter had 20 apples, Ralf had 8 apples."; preg_match_all('/\d+/', $string, $matches); foreach($matches[0] as $num) { $string = ($num > 10)? str_replace($num, 10, $string) : $string; } Quote Link to comment https://forums.phpfreaks.com/topic/136306-modifying-a-value/#findComment-711125 Share on other sites More sharing options...
KingOfHeart Posted December 10, 2008 Author Share Posted December 10, 2008 Is that for all values above 10 or just for apples? Sorry, just realized that my example was not that great for what I wanted. $string = "John had 3 apples, 100 Peter had 20 apples, Ralf had 8 apples. Susan had 30 oranges. Rick had 20 oranges"; Ok, lets say I want anyone who has more then 10 apples to be changed to 10. Anyone who has more then 20 oranges I want to be changed to 20. Your script is teaching me more about preg though at the same time, since I find it a bit confusing. Quote Link to comment https://forums.phpfreaks.com/topic/136306-modifying-a-value/#findComment-711131 Share on other sites More sharing options...
.josh Posted December 10, 2008 Share Posted December 10, 2008 That code will go through the string given and change any number over 20 to 10. This code will match all "x fruit" patterns (number, followed by space, followed by fruit) and replace the number with the max if it's higher than the max. $fruitmax is array of fruit => max $string = "John had 3 apples, 100 Peter had 20 apples, Ralf had 8 apples. Susan had 30 oranges. Rick had 20 oranges"; echo $string."<br/>"; $fruitmax = array('apples' => 10,'oranges' => 20); foreach ($fruitmax as $fruit => $max) { preg_match_all("/(\d+)\s{$fruit}/", $string, $matches); foreach ($matches[1] as $num) { $string = ($num > $max)? str_replace("$num $fruit", "$max $fruit", $string) : $string; } // end foreach match } // end foreach fruit Quote Link to comment https://forums.phpfreaks.com/topic/136306-modifying-a-value/#findComment-711140 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.