jimmygee Posted January 13, 2010 Share Posted January 13, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/188342-how-to-limit-number-of-characters-replaced-using-preg_replace/ Share on other sites More sharing options...
salathe Posted January 13, 2010 Share Posted January 13, 2010 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" Quote Link to comment https://forums.phpfreaks.com/topic/188342-how-to-limit-number-of-characters-replaced-using-preg_replace/#findComment-994284 Share on other sites More sharing options...
jimmygee Posted January 13, 2010 Author Share Posted January 13, 2010 Infinite gratitude. It works perfectly. It would have taken a PHP newbie weeks to figure that out by myself. Thanks again. Quote Link to comment https://forums.phpfreaks.com/topic/188342-how-to-limit-number-of-characters-replaced-using-preg_replace/#findComment-994307 Share on other sites More sharing options...
salathe Posted January 13, 2010 Share Posted January 13, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/188342-how-to-limit-number-of-characters-replaced-using-preg_replace/#findComment-994309 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.