Jump to content

How to limit number of characters replaced using preg_replace


jimmygee

Recommended Posts

Hi,

 

I am using the following preg_replace to change all instances of "His" to "You", "Her" to "You", and "You" to "We".

 

$patterns[0] = '/His/';

$patterns[1] = '/Her/';

$patterns[2] = '/You/';

$replacements[2] = 'Your';

$replacements[1] = 'Your';

$replacements[0] = 'We';

echo preg_replace($patterns, $replacements, $oldstring);

 

 

My problem is that not only is the preg_replace function changing "You" to "We", it is also changing "Your" to "Wer".

 

How do I modify my code so that it changes "You" to "We" but not "Your" to "Wer"?

 

Thank you for your help.

 

Jimmy

 

A common solution is to use the \b magical escape sequence which matches only at word boundaries, to quote the bible, "A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively." (\w matches a "word" character).

 

E.g. /\bYou\b/ will match "You" in "You are awesome" but not "Yours sincerely"

You're welcome, we're here to help; even if it's just knowing where to look.  :)

 

We also have a feature here where if a question is considered "solved" the thread authors can mark it as such. You just need to press the little green button labelled "mark solved" at the lower-left of this page.

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.