在下面的函数中,我想匹配关键字不区分大小写(应匹配“蓝色瑜伽垫”和“蓝色瑜伽垫”)...
但是,目前仅当关键字大小写相同时才匹配。
$mykeyword = "蓝色瑜伽垫";
$post->post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post->post_content);
// the callback function
function doReplace($matches)
{
static $count = 0;
// switch on $count and later increment $count.
switch($count++) {
case 0: return '<b>'.$matches[1].'</b>'; // 1st instance, wrap in bold
case 1: return '<em>'.$matches[1].'</em>'; // 2nd instance, wrap in italics
case 2: return '<u>'.$matches[1].'</u>'; // 3rd instance, wrap in underline
default: return $matches[1]; // don't change others.
}
}
只需添加i
对正则表达式进行修饰符以使其执行不区分大小写的匹配:
"/\b($mykeyword)\b/i"
顺便说一句,如果您还没有这样做,您需要从关键字中转义特殊的正则表达式字符。如果存在任何一个,它们可能会搞乱你的正则表达式并导致 PHP 警告/错误。称呼preg_quote() http://php.net/manual/en/function.preg-quote.php在执行更换之前:
$mykeyword_escaped = preg_quote($mykeyword, '/');
$post->post_content = preg_replace_callback("/\b($mykeyword_escaped)\b/i","doReplace", $post->post_content);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)