PHP在字符串中找到多个单词并用<;span>;标签


PHP find multiple words in string and wrap in <span> tags

我在字符串中找到关键字"painball",并将其包装在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); 

您可以使用preg_replace,向它传递一个单词数组,并使用i修饰符进行不区分大小写的匹配:

$patterns = array('/paint's?ball/i', '/airsoft/i', '/laser tag/i');
$newoutput = preg_replace($patterns, '<span style="color:red;">$0</span>', $string);

/paint's?ball/中的's?匹配零或一个空格-如果您愿意,可以使用's*来匹配零或多个空格。

简单易用的

$title  =   get_the_title($post->ID);
$arraytitle = explode(" ", $title);
for($i=0;$i<sizeof($arraytitle);$i++){
    if($i == 0){
        echo $arraytitle[0].' ';
    }elseif($i >= 0){
        echo '<span>'.$arraytitle[$i].'</span>'." ";
    }
}

使用这个:

function colorMyWord($word, $output)
{
   $target_words = array('paintball', 'paint ball', 'airsoft');
   if(in_array($target_words, $word))
   {
      $newoutput = str_ireplace($word, "<span style='"color:red;'">$word</span>", $output); 
 return $newoutput;
}

用法:

echo colorMyWord('Paintball', 'I need a Paintball');