我在字符串中找到关键字“paintball”,并将其包裹在 span 标签中以将其颜色更改为红色...
$newoutput = str_replace("Paintball", "<span style=\"color:red;\">Paintball</span>", $output);
echo $newoutput;
这行得通,但人们在现场将其写为“Paintball”、“paintball”、“Paint Ball”、“paint ball”等。
有没有更好的方法来做到这一点而不是对每个单词重复它?
理想情况下类似...
$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);
关于PHP 在字符串中查找多个单词并包装在 <span> 标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29149562/