PHP子字符串回显错误字符


PHP substr echoes incorrect characters

我有一个字符串:

"我是一家大型跨国公司的一部分":如何晋升到最高职位的建议。

我想要子字符串: ' I ' m Part

字符串存储在名为$title

的变量中我代码:

<?php echo substr( $title, 0, 9 ); ?>

writepponline返回‘I’m

,在网页上,它返回‘I&

为什么会这样?

这里的问题来自substr()不计算字符,而是字节。

你的输入字符串是多字节的;一个字符用一个或多个字节表示。确切的数量取决于字符串的编码。最有可能是UTF-8,但只有你能肯定地告诉它。

无论如何,你的问题的解决方案是mb_substr()函数,这是PHP mb扩展的一部分。

问题在于您在原始字符串中使用的引号。

如果使用常规单引号',将显示正确的输出:

$title = "'I'm Part of a big MNC': Tips on how you can rise to the top position.";
echo substr( $title, 0, 9 );
结果:

'I'm Part

问题是您的数据不是ASCII。你必须使用多字节函数,并告诉PHP在内部使用正确的编码,可能是UTF-8。

这个例子在writephponline:

中正常工作
<?php
mb_internal_encoding("UTF-8");
$string = "‘I’m Part of a big MNC’";
var_dump(mb_substr($string, 0, 9));
//output:  string(13) "‘I’m Part"