php:如何忽略preg_replace中的字母大小写?(php: How to ignore letter case within a 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>';I want to match text from a string, whilst ignoring it's letter case. My example fails if the letter cases 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>';最满意答案
好的,对这条线进行了一些修改
return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text). ')/', "<strong>$1</strong>", $str);首先,对大小写不敏感的正则表达式使用修饰符/i 。
其次,为了在正则表达式中使用$text而避免使用它,因为它可能具有特定于正则表达式的符号(它也允许您删除所有这些替换项)。
第三,不需要捕获组,使用适合$0则表达式的整个字符串部分
return preg_replace('/'.preg_quote($text, '/').'/i','<strong>$0</strong>',$str);Ok, a couple of modifications for the line
return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text). ')/', "<strong>$1</strong>", $str);First, use modifier /i for the case-insensitive regexp.
Second, escape $text for the use in regexp as it might have symbols specific for the regexp (it also allows you to remove all those replacements that you have).
Third, no need in capturing the group, use the whole part of the string that fits the regexp by $0
return preg_replace('/'.preg_quote($text, '/').'/i','<strong>$0</strong>',$str);更多推荐
发布评论