【问题标题】:str_ireplace does not work with non ASCII charectersstr_replace 不适用于非 ASCII 字符
【发布时间】:2011-07-10 11:12:18
【问题描述】:

我需要在俄语文本中突出显示搜索结果,但是当查询有不​​同的大小写时 str_ireplace() 不起作用。我已经尝试了我在manual 中犯规的所有内容,但没有任何效果。这是我尝试过的:

<?php
setlocale (LC_ALL, 'ru_RU');
$query = 'ПрОбЛеМа';
$result = 'Эта проблема нам не знакома.';

$result = str_ireplace($query, "<strong>$query</strong>", $result); // does not work
$result = preg_replace("/($query)/i", '<strong>$1</strong>', $result); // does not work
$result = mb_eregi_replace("$query", "<strong>$query</strong>", $result); // does not work
$result = ext_str_ireplace($query, "<strong>$query</strong>", $result); // from php.net - does not work
$result = highlightStr($result, $query); // from php.net - does not work

?>

有什么方法可以让它工作吗?我在这里绝望了。

PHP 5.3.3

【问题讨论】:

    标签: php regex search


    【解决方案1】:

    如果您将“u”(unicode)修饰符添加到 preg_replace,它应该可以工作:

    $result = preg_replace("/($query)/ui", '<strong>$1</strong>', $result);
    

    【讨论】:

    • 天啊,这真是天才!我多么想为此给你买杯啤酒!
    • 不错的猜测,因为非 ASCII 不会自动暗示 Unicode ;-)
    • @Álvaro G. Vicario,我猜我是在一个充满阳光的世界长大的,这里的非 ASCII 默认表示 Unicode。更不用说我的错了:)
    【解决方案2】:

    如果你使用非 ASCII/多字节,你可以使用 mb_eregi_replace

    但删除“

    $result = mb_eregi_replace($query, "<strong>$query</strong>", $result);
    

    你也可以设置你的编码:

    mb_internal_encoding("UTF-8");
    mb_regex_encoding("UTF-8");
    

    【讨论】:

    • 如何不用正则表达式来解决这个问题y?前提是指针行中的字符寄存器不能更改(!)。
    【解决方案3】:

    替换掉:

    function mb_str_ireplace ($search, $replace, $subject, &$replacements) 
    {
        return preg_replace("/$search/ui", $replace, $subject, -1, $replacements);
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 2016-10-25
      • 2013-09-21
      相关资源
      最近更新 更多