PHP - strlen返回由引号引起的不正确的字符串长度

时间:2013-09-26 09:46:32

标签: php strlen

我有来自数据库的以下字符串:让我们获取功能

如果我通过strlen运行它,它返回25个字符而不是预期的20.一个var转储显示字符串看起来像上面的那样(没有html引用等)。

如果删除单引号,strlen返回19个字符。

显然报价是返回5个字符而不是1 - 为什么?我怎么能阻止这个?

谢谢!

5 个答案:

答案 0 :(得分:4)

ASCII实体名称为' ',等于5个字符:ASCII Table

这个问题似乎与您的'被评估的事实有关,而不仅仅是被评估。 尽量让你的字符串:

$myString = 'Hello World!';

不喜欢这样:

$myString = "Hello World!";

它会读取和评估所有字符串的内容,而不仅仅是阅读,因此将您的特殊字符解释为ASCII代码。

PHP手册说:If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters

我认为您的strlen()函数是使用包含"的参数调用的,因此它会提供已评估的strlen(),而不是readed。

试试这个:

$countChars = strlen(utf8_decode($myString));

utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.

请查看this,了解有关简单和双引号之间差异的更多信息。

答案 1 :(得分:2)

不可能。

<?php
$str = "Let's Get Functional";
echo strlen($str), "\n"; // 20

Look at code output here.

如何调试?

打印每个字符的ASCII码:

$str = "Let's Get Functional";
$len = strlen($str);
for ($i = 0; $i < $len; $i++)
{
    echo "$i\t", ord($str[$i]), "\n";
}

这是结果:

0   L       76
1   e       101
2   t       116
3   '       39
4   s       115
5           32
6   G       71
7   e       101
8   t       116
9           32
10  F       70
11  u       117
12  n       110
13  c       99
14  t       116
15  i       105
16  o       111
17  n       110
18  a       97
19  l       108

答案 2 :(得分:1)

正如@deformhead已经解释的那样,您的撇号似乎已转换为HTML &apos;字符串。我的猜测是,在将字符串从数据库中取出并在其上调用strlen()之间,您可以在其间的某处调用htmlentities()。

您还可以使用CHAR_LENGTH()(MySQL)检查选择查询中从数据库中获得的字符数。

您可能会考虑的另一个问题是strlen()不适用于多字节字符,因此如果您使用的是非ASCII字符,那么最好使用具有正确编码的mb_strlen()。但是这种情况不能解释结果中5个字符的区别(strlen()计算字节而不是字符串中的字符)。

希望有所帮助。

答案 3 :(得分:0)

<?php

$string = "Let's Get Functional";

echo strlen($string);

?>

此代码返回20个字符。

答案 4 :(得分:0)

我和你有同样的问题,这可能对某人有所帮助。

单引号转换为&#34;&amp; #39;&#34;这给了我不正确的结果。 简单地用单引号替换字符串已经解决了我的问题。

$ string =&#34;让我们获得功能&#34 ;; //来自POST或数据库的字符串

echo strlen($ string); // 25

$ string = str_replace(&#34;&#39;&#34;,&#34;&#39;&#34;,$ string); echo strlen($ string); // 20