让我们说
$keyword = obama
$result = "US President Barack Obama on Wednesday signed a landmark law"
如何在$ result中出现$ keyword后,将$关键字更改为<strong></strong>
个标记?
str_replace不起作用,因为如果关键字位于lowercaps中且结果obama位于higuer上限,则无法替换它。
由于
编辑:找到答案,万一有人需要,这就是代码
$myWords = array($keyword);
function boldText($arrWords, $strSubject)
{
if (!is_array($arrWords)) return;
foreach ($arrWords as $strWord)
{
$strSubject = preg_replace('@(' . preg_quote($strWord, '@') . ')@i', "<b>\\1</b>", $strSubject);
}
return $strSubject;
}
答案 0 :(得分:1)
str_replace (ucfirst($keyword), "<strong>" . $keyword . "</strong">, $result);
或使用不区分大小写的正则表达式。
答案 1 :(得分:0)
<?php
function boldText($string, $array) {
$string = strip_tags($string);
return preg_replace('~('.implode('|', $array).'[a-zA-Z]{0,45})(?![^<]*[>])~is', '<strong>$0</strong>', $string );
}
?>
来自http://php.bigresource.com/bold-string-from-array-of-keywords-HLRL2A8c.html
答案 2 :(得分:0)
您可以使用str_replace:
str_replace ( mixed $keyword, mixed '<strong>' . $keyword . '</strong>', mixed $result)
这会将$关键字替换为自身,并被<strong>
标记包围。
答案 3 :(得分:0)
我确定可能还有其他方法,但我会使用preg_replace()。类似的东西:
$result = preg_replace($keyword , "<strong>$keyword</strong>" , $result);