[英]PHP find multiple words in string and wrap in <span> tags
Im finding keyword "paintball" in a string, and wrapping it in span tags to change it colour to red like this... 我在字符串中找到关键字“彩弹”,并将其包裹在span标签中,将其颜色更改为红色,如下所示...
$newoutput = str_replace("Paintball", "<span style=\"color:red;\">Paintball</span>", $output);
echo $newoutput;
Which works, but people are writing it in the field as "Paintball", "paintball", "Paint Ball", "paint ball" etc. 哪个有效,但是人们在现场写作“彩弹射击”,“彩弹射击”,“油漆球”,“油漆球”等。
Is there a better way of doing this rather than repeating it for every word? 有没有更好的方法来做到这一点,而不是为每个单词重复它?
Ideally something like... 理想情况下......
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
$newoutput = str_replace("($words)", "<span>$1</span>", $output);
But im not sure how to write it. 但我不知道如何写它。
Ok, so a mixture of answers got me here... 好的,所以答案的混合物让我来到这里......
$newoutput = preg_replace("/(paint\s*ball|airsoft|laser\s*tag)/i", "<span>$1</span>", $output);
echo $newoutput;
And it works perfectly, thank you very much! 而且效果很好,非常感谢!
This should work for you: 这应该适合你:
(Here I just use preg_replace()
with the modifier i
for case insensitivity) (这里我只使用
preg_replace()
和修饰符i
来表示不区分大小写)
<?php
$output = "LaSer Tag";
$newoutput = preg_replace("/(Airsoft|Paintball|laser tag)/i", "<span style=\"color:red;\">$1</span>", $output);
echo $newoutput;
?>
EDIT: 编辑:
Besides that this is invalid syntax: 除此之外,这是无效的语法:
$words = "Paintball", "paintball", "Paint Ball", "paint ball";
and you probably meant this: 你可能意味着这个:
$words = ["Paintball", "paintball", "Paint Ball", "paint ball"];
//^ See here array syntax ^
You can use something like this then 你可以使用这样的东西
$newoutput = preg_replace("/(" . implode("|", $words) . ")/i", "<span style=\"color:red;\">$1</span>", $output);
You could use preg_replace
, passing it an array of words and doing a case-insensitive match using the i
modifier: 你可以使用
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);
The \\s?
\\s?
in /paint\\s?ball/
matches zero or one spaces - you could use \\s*
to match zero or more instead if you preferred. in
/paint\\s?ball/
匹配零个或一个空格 - 如果您愿意,可以使用\\s*
匹配零或更多。
Simple and easy to use 简单易用
$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>'." ";
}
}
use this: 用这个:
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;
}
Usage : 用法:
echo colorMyWord('Paintball', 'I need a Paintball');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.