Hi,
I'd like to remove all aaa and bbb (whole word) from my string. I use the code below:
$str=" aaa bbb aaa aaa aaa laaa bbb ";
echo preg_replace("/\s(aaa|bbb)\s/", ' ', $str);
The output is " bbb aaa laaa ".
-->bbb and aaa are still there while it must be removed?
What's wrong with the pattern I used?
(The pattern above works fine if I replace \s by \b - but I don't want to use \b because \b does not work as expected if my string $str contains unicode words).
Could somebody please help me solve the issue?
remove a list of words from a string
Moderator: General Moderators
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: remove a list of words from a string
The single white space you're replacing it with will NOT be used in the following match of your regex. So, the first "_aaa_" is matched in your string (the underscores are spaces) and replaced by a white space but the next substring in your text will be "bbb_" (no space in front of it!) which does not match your regex.sqth wrote:Hi,
I'd like to remove all aaa and bbb (whole word) from my string. I use the code below:
$str=" aaa bbb aaa aaa aaa laaa bbb ";
echo preg_replace("/\s(aaa|bbb)\s/", ' ', $str);
The output is " bbb aaa laaa ".
-->bbb and aaa are still there while it must be removed?
What's wrong with the pattern I used?
Use look arounds instead:sqth wrote:(The pattern above works fine if I replace \s by \b - but I don't want to use \b because \b does not work as expected if my string $str contains unicode words).
Could somebody please help me solve the issue?
Code: Select all
echo preg_replace('/(?<=\s)(aaa|bbb)(?=\s)/', '', $str);Re: remove a list of words from a string
Thank you so much for your help! 
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: remove a list of words from a string
You're welcome.sqth wrote:Thank you so much for your help!