Reputation: 543
I have following php code that removes whole word that matches the pattern
$patterns = ["re", "get", "ER"];
$string = "You are definitely getting better today";
$alternations = implode('|', $patterns);
$re = '(?!(?<=\s)(?:'.$alternations.')(?=\s))\S*(?:'.$alternations.')\S*';
$string = preg_replace('#'.$re.'#', '', $string);
$string = preg_replace('#\h{2,}#', ' ', $string);
echo $string;
I want two modifications
If $string is
You are definitely getting
better
today
Output must be
You definitely
today
Regards,
Upvotes: 0
Views: 59
Reputation: 626748
You may use
$patterns = ["re", "get", "ER"];
$string = "You are definitely getting\nbetter\ntoday";
$alternations = implode('|', $patterns);
$re = '\R?(?!(?<=\s)(?:'.$alternations.')(?=\s))\S*(?:'.$alternations.')\S*';
$string = preg_replace('#'.$re.'#i', '', $string);
$string = preg_replace('#\h{2,}#', ' ', $string);
echo $string;
See the PHP demo.
While the i
modifier provides the case insensitivity to regex matching, another, less obvious thing here is that you need to add an optional line break pattern.
That line break can be matched in various ways, but in PHP PCRE, you may easily match it with \R
construct.
Adding a ?
quantifier after it, you may make it match 1 or 0 times, i.e. make it optional, so that the whole pattern could still match at the start of the string.
Upvotes: 1