我正在尝试突出显示/加粗字符串中的匹配词。以下函数适用于英语,但不适用于 Unicode 支持。我试图在正则表达式规则中添加 Unicode 支持的u
,但对我不起作用。
function highlight_term($text, $words)
{
preg_match_all('~[A-Za-z0-9_äöüÄÖÜ]+~u', $words, $m);
if( !$m )
{
return $text;
}
$re = '~(' . implode('|', $m[0]) . ')~i';
return preg_replace($re, '<b>$0</b>', $text);
}
$str = "ह ट इ ड यन भ भ और द";
echo highlight_term($str, 'और');
输出
��� ��� ��� ��� ������ ��� ��� ������ ���
预期产出
ह ट इ ड यन भ भ ःर द
修复当前的方法
请注意,您可以将第一个正则表达式更改为~[p{L}p{M}]+~u
以匹配所有 Unicode 字母(p{L}
修饰符u
成为 Unicode 感知并匹配任何 Unicode 字母(和变音符号(p{M}
匹配组合标记(,并将u
修饰符添加到第二个preg_replace
:
function highlight_term($text, $words)
{
$i = preg_match_all('~[p{L}p{M}]+~u', $words, $m);
if( $i == 0 )
{
return $text;
}
$re = '~' . implode('|', $m[0]) . '~iu';
return preg_replace($re, '<b>$0</b>', $text);
}
$str = "ह ट इ ड यन भ भ और द";
echo highlight_term($str, 'और');
结果:ह ट इ ड यन भ भ <b>और</b> द
.
查看 PHP 演示
您需要在第二个正则表达式中使用u
修饰符,因为传递给模式的文本是 Unicode,并且您仍然可以使用 Unicode 字符串。第二个正则表达式中不需要外括号,因为您只对整个匹配值感兴趣(使用反向引用替换$0
(。
更好的方式
您可以将单词数组传递给突出显示函数,并且仅将整个单词与单词边界直接传递给preg_replace
函数匹配:
function highlight_term($text, $words)
{
return preg_replace('~b(?:' . implode("|", $words) . ')b~u', '<b>$0</b>', $text);
}
$str = "ह ट इ ड यन भ भ और द";
echo highlight_term($str, ['और','भ']);
// => ह ट इ ड यन <b>भ</b> <b>भ</b> <b>और</b> द
查看此 PHP 演示