我在字符串中找到关键字“彩弹”,并将其包裹在span标签中,将其颜色更改为红色,如下所示…
$newoutput = str_replace("Paintball", "<span style=\"color:red;\">Paintball</span>", $output);
echo $newoutput;
哪个有效,但是人们在现场写作“彩弹射击”,“彩弹射击”,“油漆球”,“油漆球”等.
有没有更好的方法来做到这一点,而不是为每个单词重复它?
理想情况下……
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
$newoutput = str_replace("($words)", "<span>$1</span>", $output);
但我不知道如何写它.
好的,所以答案的混合物让我来到这里……
$newoutput = preg_replace("/(paint\s*ball|airsoft|laser\s*tag)/i", "<span>$1</span>", $output);
echo $newoutput;
而且效果很好,非常感谢!
解决方法:
这应该适合你:
(这里我只使用preg_replace()
和修饰符i来表示不区分大小写)
<?PHP
$output = "LaSer Tag";
$newoutput = preg_replace("/(Airsoft|Paintball|laser tag)/i", "<span style=\"color:red;\">$1</span>", $output);
echo $newoutput;
?>
编辑:
除此之外,这是无效的语法:
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
你可能意味着这个:
$words = ["Paintball", "paintball", "Paint Ball", "paint ball"];
//^ See here array Syntax ^
你可以使用这样的东西
$newoutput = preg_replace("/(" . implode("|", $words) . ")/i", "<span style=\"color:red;\">$1</span>", $output);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。