这是我目前在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
答案 0 :(得分:1)
我同意@chris85 的评论。您没有理由为此任务使用正则表达式。
只需用标记包装的文字字符串替换文字字符串即可。
dcbd
baac
caab
dbcd
如果您需要不区分大小写的支持,那么我同意 @BrandoneHorsley 的观点,return str_replace($keyword, '<span class="h">' . $keyword . '</span>', $string);
就足够了。
str_ireplace()
至于您对特殊字符的关注,我们敬爱的@deceze has this to say/demonstrate as the highest voted comment in the php docs:
<块引用>请注意,所有关于 mb_str_replace 的讨论都在 评论很没有意义。 str_replace 与 多字节字符串
答案 1 :(得分:0)
使用捕获组:
function highlight_keywords($keyword, $string) {
return preg_replace("/(\p{L}*?)(".preg_quote($keyword).")(\p{L}*)/ui", "$1<span class=\"h\">$2</span>$3", $string);
}