Php: how to ignore case of letters in preg_replace?

I want to combine text with a string, ignoring its alphabetic case. My example fails if the letters are not identical.

/*
  $text:  fOoBaR
  $str:   little brown Foobar
  return: little brown <strong>Foobar</strong>
*/
function bold($text, $str) {
    // This fails to match if the letter cases are not the same
    // Note: I do not want to change the returned $str letter case.
    return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).')/', "<strong>$1</strong>", $str);
}

$phrase = [
    'little brown Foobar' => 'fOoBaR',
    'slash / slash' => 'h / sl',
    'spoon' => 'oO',
    'capital' => 'CAPITAL',
];

foreach($phrase as $str => $text)
    echo bold($text, $str) . '<br>';

      

+3


source to share


2 answers


Ok, a few modifications to the line

return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).
                     ')/', "<strong>$1</strong>", $str);

      

First, use a modifier /i

for case insensitive regex.



Second, escape is $text

for use in regexp since it can have regexp-specific characters (it also allows you to remove all those replacements you have).

Third, there is no need to capture the group, use the entire part of the string that matches the regex $0

return preg_replace('/'.preg_quote($text, '/').'/i','<strong>$0</strong>',$str);

      

+4


source


Add a case insensitive modifier i

to the regular expression.



function bold($text, $str) {
    // This fails to match if the letter cases are not the same
    // Note: I do not want to change the returned $str letter case.
    return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).')/i', "<strong>$1</strong>", $str);
}

      

+2


source







All Articles