php:如何忽略preg

编程入门 行业动态 更新时间:2024-10-28 08:28:28
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);

更多推荐

本文发布于:2023-04-29 09:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:php   preg

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!