繁体   English   中英

突出显示搜索中的多个关键字(非英语字符)

[英]Highlight multiple keywords in search (non-english characters)

找到了此功能以在线程中突出显示搜索字符串中的关键字

function highlight($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
    return preg_replace($re, '<b>$0</b>', $text);
}

但是它不适用于非英语字符,我如何调整它使其与åäöô等兼容。

您确定要搜索Unicode字符吗? \\ w仅匹配[a-zA-Z0-9_]。

例如,这匹配波斯数字:

preg_match( "/[^\x{06F0}-\x{06F9}\x]+/u" , '۱۲۳۴۵۶۷۸۹۰' );

来源: http : //php.net/manual/en/function.preg-match.php

只需使用要匹配的字符创建一个字符类。

页面加载所需的编码后,最好使用JS来实现:

function paint_keys( str_to_replace , words ){
temp_reg = str_to_replace;
if( /\s/g.test( temp_reg ) ) temp_reg = temp_reg.split( " " ); // Breaking our searching keywords into an array;
else return words.split( temp_reg ).join( "<span class='painted'>" + temp_reg + "</span>" );
for( z = 0 ; z < temp_reg.length ; z++ ){
    if( temp_reg[ z ] != "" ) words = words.split( temp_reg[ z ] ).join( "<span class='painted'>" + temp_reg[ z ] + "</span>" );
}
return words;
}

当然,您可以根据需要替换<span class='painted'>" + temp_reg + "</span>

如果您只需要使用php来完成它-使用通过explode( "\\s" , $words );破坏键来排列数组的原理explode( "\\s" , $words ); -这只会为您提供一个符号数组,然后循环为该数组中的每个单词替换字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM