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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.