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

时间:2015-03-19 16:05:51

标签: php

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

它完美无缺,非常感谢!

4 个答案:

答案 0 :(得分: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;

?>

修改

除此之外,语法无效:

$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); 

答案 1 :(得分:3)

你可以使用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);

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

答案 2 :(得分:1)

简单易用

$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>'." ";
    }
}

答案 3 :(得分:0)

使用它:

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');