0
内の文字列の一致する部分を強調表示する方法:これはPHPで私の現在の関数であるPHP
function highlight_keywords($keyword, $string) {
return preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<span class=\"h\">$0</span>", $string);
}
CSSクラス:
span.h {
font-weight: 700;
color: @color_action;
}
例:
echo highlight_keywords('anto', 'Andres Santos');
問題結果は次のとおりです。
Andres <span class="h">Santos</span>
...そして、それは以下のようになります。
Andres S<span class="h">anto</span>s
あなたは、\ pを{L} *を持っていないのはなぜ?パターンの一部? "preg_replace("/"。preg_quote($ keyword)。"/" $ 0"、$ string); ' –
@BrandonHorsleyあなたは正しいです。あなたの答えは、以下の最初の回答よりもさらに簡単です。 – andufo
正規表現を使用して静的な値と一致させる必要はありません。大文字小文字を区別しない場合は 'return str_replace($ keyword、 ''。$ keyword。 ''、$ string); ' – chris85