Jump to content

Modifying a value


KingOfHeart

Recommended Posts

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.

 

Link to comment
https://forums.phpfreaks.com/topic/136306-modifying-a-value/#findComment-711131
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/136306-modifying-a-value/#findComment-711140
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.