【问题标题】:substr() return incorrect number of characterssubstr() 返回不正确的字符数
【发布时间】:2017-08-07 02:52:56
【问题描述】:

substr() 返回 28 个字符而不是 25 个字符。

$nature_goods是输入框,用户可以在其中输入包含特殊字符的字符串。

代码

$nature_goods =  "Nature quantityyy of goods is nice 120pcs 1*X23X24898";
echo strlen($nature_goods);
echo "<br>";
echo substr($nature_goods, 0,25);
echo "<br>";
echo strlen(substr($nature_goods, 0,25));
echo "<br>";
echo substr($nature_goods, 25,50);
echo "<br>";
echo strlen(substr($nature_goods, 25,50));
echo "<br>";

输出

53
Nature quantityyy of good
25
s is nice 120pcs 1*X23X24898
28

我试过mb_substr()mb_strlen(),但我没有看到任何多字节字符串造成问题。有人能指出错误吗?

【问题讨论】:

  • 没有错 - 你的输出是正确的。从 s is..... 开始只有 28 个字符,所以 substr($nature_goods, 25,50); 将只返回 28
  • 但是 substr(25,50) 必须返回 25 个字符对吗?
  • 不,它会从第 25 位检查 manual 返回最多 50 个字符,如果你只想要 25 个字符,你应该使用 substr($nature_goods, 25,25);
  • 哦,是的,谢谢 :) 我怎样才能结束这个问题?
  • 我想只是删除问题。对未来的读者没有多大用处

标签: php substring substr


【解决方案1】:

您使用的 substr 不正确。

您正在使用传递给函数的最后一个值作为端点而不是长度,例如抓取 25 到 50 之间的字符,而不是使用应该使用的 substr,正如您所写的那样, 跳过前 25 个字符后抓取 50 个字符。

最后的函数调用应该是 substr($nature_goods, 25, 25);如果您期望收到 25 个字符作为回报。

substr 的预期值:

substr (字符串 $string , int $start , int $length )

这里有完整的文档:

http://php.net/manual/en/function.substr.php

【讨论】:

    【解决方案2】:

    在substr()函数中第三个参数用来设置长度而不是设置位置。更多详情请访问

    http://php.net/manual/en/function.substr.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2016-09-10
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多