我正在尝试在字符串中加粗单词的每个实例,并在单词的第一个实例之前删除字符串中的所有内容。
我正在使用str_replace()
和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;
}
我想要的是:
快速棕色狐狸跳过 懒狗
或
<span class="found">the</span> quick brown fox jumped over <span class="found">the</span> lazy dog
回应时。
但我得到的是:
快速的棕色狐狸跳过懒狗
或
the quick brown fox jumped over the lazy dog
回应时。
我做错了什么?
答案 0 :(得分:3)
$edited = stristr($sentence, $word);
$edited = str_ireplace($word, '<span class="found">'.$word.'</span>', $edited);
或者更好(保留原始案例,只加粗整个$word
):
$edited = stristr($sentence, $word);
$edited = preg_replace('~\b(' . preg_quote($word, '~') . ')\b~i', '<span class="found">$1</span>', $edited);