php:如何忽略 preg_replace 中的字母大小写?

dit*_*tto 3 php preg-replace

我想匹配字符串中的文本,同时忽略它的字母大小写。如果字母大小写不相同,我的示例就会失败。

/*
  $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>';
Run Code Online (Sandbox Code Playgroud)

Che*_*ery 5

好的,对该行进行一些修改

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

首先,/i对不区分大小写的正则表达式使用修饰符。

其次,$text在正则表达式中使用转义,因为它可能具有特定于正则表达式的符号(它还允许您删除所有这些替换)。

第三,不需要捕获组,使用适合正则表达式的字符串的整个部分$0

return preg_replace('/'.preg_quote($text, '/').'/i','<strong>$0</strong>',$str);
Run Code Online (Sandbox Code Playgroud)