substr() return incorrect number of characters

我是研究僧i 提交于 2019-12-02 18:03:23

问题


substr() is returning 28 characters instead of 25.

$nature_goods is the input field, where user can enter string containing special characters.

Code

$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>";

Output

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

I tried mb_substr() and also mb_strlen(), but I do not see any multibyte string creating a problem. Can someone point out the mistake?


回答1:


You are using substr incorrectly.

You are using the last value passed to the function as an end point rather than a length, as in grab the characters between 25 and 50, instead of using substr as it supposed to be used, which, as you have written it, is grab 50 characters after skipping the first 25 characters.

The final function call should be substr($nature_goods, 25, 25); if you are expecting to receive 25 characters in return.

Values expected for substr:

substr ( string $string , int $start , int $length )

Full documentation here:

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




回答2:


In substr() function third parameter is used to set the length not to set the position. For more details please visit

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



来源:https://stackoverflow.com/questions/42825484/substr-return-incorrect-number-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!