我在字符串中找到关键字“彩弹”,并将其包装在跨度标签中,将其颜色改为如下所示的红色.
$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;而且效果很好,非常感谢!
发布于 2015-03-19 16:11:12
这应该适用于你:
(在这里,我只使用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); 发布于 2015-03-19 16:15:56
您可以使用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*来匹配零或更多。
发布于 2016-01-29 15:29:39
简单易用
$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>'." ";
}
}https://stackoverflow.com/questions/29149562
复制相似问题