Jump to content

How to limit number of characters replaced using preg_replace


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.

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.