不区分大小写 preg_replace_callback
在下面的函数中,我想匹配关键字不区分大小写(应匹配“Blue Yoga Mats”和“blue Yoga mats”)...
但是,目前仅在关键字大小写相同时才匹配。
$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.
}
}
In the function below, I want to match the keyword case insensitive (should match "Blue Yoga Mats" and "blue yoga mats")...
However, it currently only matches if the keyword is the same case.
$mykeyword = "Blue Yoga Mats";
$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.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需将
i
修饰符添加到您的正则表达式中即可使其执行不区分大小写的匹配:顺便说一句,如果您还没有这样做,您需要从关键字中转义特殊的正则表达式字符。如果存在任何一个,它们可能会搞乱你的正则表达式并导致 PHP 警告/错误。在执行之前调用
preg_quote()
替代品:Simply add the
i
modifier to your regex to make it perform a case insensitive match:By the way, if you haven't already, you need to escape special regex characters from your keyword. In case any are present, they could screw up your regex and cause PHP warnings/errors. Call
preg_quote()
before you perform the replacement:将“i”修饰符添加到您的正则表达式中:
Add the "i" modifier to your regexp:
使用
TOKENregexpTOKENi
执行不区分大小写的搜索。有关完整详细信息,请参阅 PHP 手册中的模式修饰符关于修饰符。
Use
TOKENregexpTOKENi
to perform case-insensitive searches.See Pattern Modifiers in the PHP manual for full details on modifiers.
使用 /i 修饰符:
Use the /i modifier:
您还可以使用 T-Regx 库:
此外,使用
$mykeyword
可能会导致用户输入字符来打破您的模式。通过T-Regx,您可以使用准备好的模式,然后构建你的模式:You can also use T-Regx library:
Also, use of
$mykeyword
might cause user-input characters to break your pattern. With T-Regx you can use Prepared Patterns and just build your pattern: