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

标签 php

我在字符串中找到关键字“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/

相关文章:

php - 测试我自己的 composer 包不起作用

php - 如何解决 PHP lookbehind 固定宽度限制?

php - 远程添加 WordPress 帖子到我的博客,但是如何添加图片?

php - PHP 中的对象比较

php - 更新数据在 Php 和 MySql 中不起作用

php - MYSQL - 从获取的数组中选择特定值

php - 检查记录是否已存在于 mySQL 数据库中

php - 在同一查询中选择+插入

php - MySql 特定字符之前的 WHERE LIKE?

php - 克隆 Dbal 连接以在重复的 Get_Affected_Rows 上执行插入操作