PHP: 特殊字符在子串中变成问号图标
PHP: Special char becomes question mark icon in substring
我的子字符串函数有问题。当一个特殊字符是结果子字符串的最后一个字符时(只有那时!!!),这个字符被表示为一个带有问号的图标。
这是我的代码:
$string = 'This is a string and when a German word with a special char like "Tür" appears and the special char ü is the last character of the substring it gets represented as an icon with question mark';
echo substr($string,0,102). "...";
结果:
This is a string and when a German word with a special char like "Tür"
appears and the special char �...
我怎样才能避免这种情况?
听起来你正在使用 8 位字符串函数来处理 unicode 字符。那行不通。
您应该安装 mbstring
软件包并在 php 配置中启用 "mbstring function overloading"。这将注意以静默方式覆盖所有相关的字符串处理函数,以使用它们的多字节安全等效函数,这样您就不必更改代码。
该 "mbstring" 扩展有许多配置选项。检查您的 php.ini
配置文件并浏览它们。您会发现 mbstring.func_overload
命令可能要设置为值 7
,以便覆盖 所有 这样的函数。更改该配置后,您必须重新启动 http 服务器进程,以便加载新配置。您还可以通过在测试脚本中使用著名的 phpinfo()
函数来检查。
另一种方法是不配置这个最重要的自动化功能,而是手动移植您的代码以直接使用这些功能。为此,您必须将代码中的 all 字符串函数调用替换为它们的等效函数名称。因此,例如 mb_substr(...)
而不仅仅是 substr(...)
。
您也真的想开始阅读您使用的工具的文档。这里对那些"multi byte string"函数的介绍很有意思。它应该可以帮助您了解这一切的含义以及您必须注意的事项:http://php.net/manual/en/book.mbstring.php
您应该使用 mb_substr
函数。
我的子字符串函数有问题。当一个特殊字符是结果子字符串的最后一个字符时(只有那时!!!),这个字符被表示为一个带有问号的图标。
这是我的代码:
$string = 'This is a string and when a German word with a special char like "Tür" appears and the special char ü is the last character of the substring it gets represented as an icon with question mark';
echo substr($string,0,102). "...";
结果:
This is a string and when a German word with a special char like "Tür" appears and the special char �...
我怎样才能避免这种情况?
听起来你正在使用 8 位字符串函数来处理 unicode 字符。那行不通。
您应该安装 mbstring
软件包并在 php 配置中启用 "mbstring function overloading"。这将注意以静默方式覆盖所有相关的字符串处理函数,以使用它们的多字节安全等效函数,这样您就不必更改代码。
该 "mbstring" 扩展有许多配置选项。检查您的 php.ini
配置文件并浏览它们。您会发现 mbstring.func_overload
命令可能要设置为值 7
,以便覆盖 所有 这样的函数。更改该配置后,您必须重新启动 http 服务器进程,以便加载新配置。您还可以通过在测试脚本中使用著名的 phpinfo()
函数来检查。
另一种方法是不配置这个最重要的自动化功能,而是手动移植您的代码以直接使用这些功能。为此,您必须将代码中的 all 字符串函数调用替换为它们的等效函数名称。因此,例如 mb_substr(...)
而不仅仅是 substr(...)
。
您也真的想开始阅读您使用的工具的文档。这里对那些"multi byte string"函数的介绍很有意思。它应该可以帮助您了解这一切的含义以及您必须注意的事项:http://php.net/manual/en/book.mbstring.php
您应该使用 mb_substr
函数。