PHP在字符串中查找多个单词并包装在<span>标记中

Col*_*ins 3 php

我在字符串中找到关键字"paintball",并将其包装在span标签中,将其颜色更改为红色,如下所示......

$newoutput = str_replace("Paintball", "<span style=\"color:red;\">Paintball</span>", $output); 

echo $newoutput;
Run Code Online (Sandbox Code Playgroud)

哪个有效,但是人们在现场写作"彩弹射击","彩弹射击","油漆球","油漆球"等.

有没有更好的方法来做到这一点,而不是为每个单词重复它?

理想情况下......

$words = "Paintball", "paintball", "Paint Ball", "paint ball";

$newoutput = str_replace("($words)", "<span>$1</span>", $output);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何写它.

好的,所以答案的混合物让我来到这里......

$newoutput = preg_replace("/(paint\s*ball|airsoft|laser\s*tag)/i", "<span>$1</span>", $output); 
    echo $newoutput;
Run Code Online (Sandbox Code Playgroud)

而且效果很好,非常感谢!

Riz*_*123 9

这应该适合你:

(这里我只使用preg_replace()修饰符i来区分大小写)

<?php

    $output = "LaSer Tag";
    $newoutput = preg_replace("/(Airsoft|Paintball|laser tag)/i", "<span style=\"color:red;\">$1</span>", $output); 
    echo $newoutput;

?>
Run Code Online (Sandbox Code Playgroud)

编辑:

除此之外,这是无效的语法:

$words = "Paintball", "paintball", "Paint Ball", "paint ball";
Run Code Online (Sandbox Code Playgroud)

你可能意味着这个:

$words = ["Paintball", "paintball", "Paint Ball", "paint ball"];
       //^ See here array syntax                              ^
Run Code Online (Sandbox Code Playgroud)

你可以使用这样的东西

$newoutput = preg_replace("/(" . implode("|", $words) . ")/i", "<span style=\"color:red;\">$1</span>", $output); 
Run Code Online (Sandbox Code Playgroud)

  • 不需要捕获组,您可以将其删除并使用“$0”代替“$1”。 (2认同)