PHP在字符串中查找多个单词并包装在标签中

我在字符串中找到关键字“彩弹”,并将其包裹在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); 

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...