简体   繁体   English

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

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

Found this function to highlight keywords in a search string in the thread highlight multiple keywords in search 找到了此功能以在线程中突出显示搜索字符串中的关键字

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);
}

But it does not work for non-english characters, how can I tweak it to work with eg å ä ö ô etc. 但是它不适用于非英语字符,我如何调整它使其与åäöô等兼容。

Are you sure you are searching for unicode characters? 您确定要搜索Unicode字符吗? \\w Only matches [a-zA-Z0-9_]. \\ w仅匹配[a-zA-Z0-9_]。

For example this matches persian digits : 例如,这匹配波斯数字:

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

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

Just create a character class with the characters you want to match. 只需使用要匹配的字符创建一个字符类。

You better do it with JS after the page loads it with needed encoding: 页面加载所需的编码后,最好使用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;
}

Of course, you can replace the <span class='painted'>" + temp_reg + "</span> to whatever you need. 当然,您可以根据需要替换<span class='painted'>" + temp_reg + "</span>

If you need it to be done by php only - use the principle of breaking the keys to array by explode( "\\s" , $words ); 如果您只需要使用php来完成它-使用通过explode( "\\s" , $words );破坏键来排列数组的原理explode( "\\s" , $words ); - that will give you an array of symbols only and then loop to replace the string for each word in the array. -这只会为您提供一个符号数组,然后循环为该数组中的每个单词替换字符串。

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

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