DMP
DMP

Reputation: 543

Modify my regex so that pattern search should not be case sensitive

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

  1. The pattern search should not be case sensitive e.g. the pattern ER must remove better in $string
  2. If removed word in $string have line breaks before or after it, only one line break should be removed.

If $string is

You are definitely getting
better
today

Output must be

You definitely
today

Sample PHP Code

Regards,

Upvotes: 0

Views: 59

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions