1

我需要比较字符串和匹配名称,即使它们的拼写方式不同。例如DÉSIRÉ-Smith应该匹配Desireesmith以及 Desiree 或Desi'ree Smith

所以我有以下方法,它使用 PHP-CLI 在命令行中完美运行:

    <?
    class Alike {
      static function convertAlike($string) {
        // in case the first and last name or two first names are mixed up
        $parts = preg_split('/[\s\-\.\_]/', $string, -1, PREG_SPLIT_NO_EMPTY);
        sort($parts);
        $string = implode($parts);

        $string = iconv('UTF-8', 'ASCII//TRANSLIT', $string); // transliterate
        $string = strtolower($string); // lowercase
        $string = preg_replace('/[^a-z]/','',$string); // remove everything but a-z
        $string = preg_replace('{(.)\1+}','$1',$string); // remove duplicate chars
        return $string;
      }
      static function compareAlike($string1,$string2) {
        return (strcmp(Alike::convertAlike($string1),Alike::convertAlike($string2)) === 0) ? true : false;
      }
    }
    echo Alike::convertAlike("DÉSIRÉ-Smith").PHP_EOL; // desiresmith
    echo Alike::convertAlike("Desireesmith").PHP_EOL; // desiresmith
    echo Alike::convertAlike("Desi'ree Smith").PHP_EOL; // desiresmith
    echo Alike::convertAlike("René Röyßeå likes special characters ½ € in ©").PHP_EOL; // reneroysealikespecialcharacterseurinc

    var_dump(Alike::compareAlike("DÉSIRÉ-Smith","Desireesmith")); // true
    var_dump(Alike::compareAlike("Desireesmith","Desi'ree Smith")); // true
    var_dump(Alike::compareAlike("summer","winter")); // false
    ?>

然而,在我作为模块Server version: Apache/2.2.14 (Ubuntu)运行的网站中PHP Version 5.3.2-1ubuntu4.2,我总是得到问题标志。有趣的是,错误必须发生在这一行

$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string); // transliterate

因为之后我可以看到每个没有被音译的字符,但是那些应该被 ascii 字符替换的字符变成了问号。

我尝试了输入/输出字符串编码和 iconv 内部、输入和输出编码设置以及语言环境设置的所有可能组合。我什至做了 chmod -R 777 /usr/lib/gconv 并将其移至我的工作目录。

但是我看到这个错误报告在他的邮件列表上: http ://bugs.php.net/bug.php?id=44096

[2010-06-07 21:22 UTC] icovt at yahoo dot com
mod_php iconv() is not working properly if your apache is chrooted and you do not 
have the content of /usr/lib/gconv/ folder into your relative chroot path (i.e. 
/your/chroot/path/usr/lib/gconv/). 
You can simply do: 
cp /usr/lib/gconv/* /your/chroot/path/usr/lib/gconv/
... and re-try.

This was a fix for me, hope this could save time for somebody else.

P.S. Btw, initially iconv() called from command line (using php cli) was OK.

我试过我的 www-data 用户在 /var/www/ 的家中,最后我得到了文件夹 /var/www/usr/lib/gconv/ 以及 /var/www/myproject/usr/lib/gconv /

仅供参考:我有编码检测和转码功能,以确保传递正确的编码,但为了清楚起见将它们删除,因为如果你输入 utf8 字符串就不需要它们,一切都应该没问题......

有任何想法吗?

4

1 回答 1

2

发现语言环境设置不正确,我尝试设置它失败了,因为系统上可用的语言环境实际上被命名为与手册页示例不同的名称(根据它们的编码!)一个简单的locale -a揭示;O)

setlocale(LC_ALL, "en_US.utf8");

这实际上完成了工作!

现在这个功能完美运行。

现在它清楚为什么它也可以从控制台工作,因为语言环境是从当前用户的 shell 设置导入的;)它实际上只需要设置任何语言环境。当我们转换为每个人都平等的 ascii 时,哪一个并不重要,只有一些人比其他人更平等:)

小心设置实际安装在系统中的语言环境并检查 setlocale 的结果,因为如果没有安装语言环境或名称拼写错误,您将不会更改任何内容。

于 2010-08-24T21:39:13.883 回答