我试图将字符串中单词的每个实例加粗,并删除字符串中第一个单词实例之前的所有内容。
我在用着str_replace()
and stristr()
这样做,但输出不符合预期。该单词的第一个实例之前的所有内容都被切断,但当我回显该字符串时,该单词的实例不是粗体。
这是我的代码:
$word="the";
$sentence = "Hello, did you hear the quick brown fox jumped over the lazy dog";
$edited = stristr((str_replace($word, ("<span class=\"found\">".$word."</span>"), ($sentence))), $word);
echo $edited;
以及使该类变为粗体的 CSS:
.found{
font-weight:bold;
font-weight:700;
}
我想要的是这样的:
the敏捷的棕色狐狸跳过了the懒狗
or
<span class="found">the</span> quick brown fox jumped over <span class="found">the</span> lazy dog
当回响时。
但我得到的是这样的:
敏捷的棕色狐狸跳过了那只懒狗
or
the quick brown fox jumped over the lazy dog
当回响时。
我究竟做错了什么?
$edited = stristr($sentence, $word);
$edited = str_ireplace($word, '<span class="found">'.$word.'</span>', $edited);
Demo.
或者更好(保留原始大小写,仅将整个内容加粗$word
s):
$edited = stristr($sentence, $word);
$edited = preg_replace('~\b(' . preg_quote($word, '~') . ')\b~i', '<span class="found">$1</span>', $edited);
另一个演示.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)