In PHP, you can directly use the substr() function to remove the last few characters in reverse order. The syntax format is "substr(string object, 0,-x)". The parameter x is the number of characters that need to be removed; if If successful, the string with the characters removed will be returned. If failed, FALSE will be returned, or an empty string will be returned.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php remove the last few characters
<?php header('content-type:text/html;charset=utf-8'); $str = '123,234,345,'; echo "原字符串:",$str,'<br/>'; echo "去掉最后1个字符的字符串:",substr($str,0,-1),'<br/>'; echo "去掉最后2个字符的字符串:",substr($str,0,-2),'<br/>'; echo "去掉最后3个字符的字符串:",substr($str,0,-3),'<br/>'; echo "去掉最后4个字符的字符串:",substr($str,0,-4),'<br/>'; echo "去掉最后5个字符的字符串:",substr($str,0,-5); ?>
Output:
原字符串:123,234,345, 去掉最后1个字符的字符串:123,234,345 去掉最后2个字符的字符串:123,234,34 去掉最后3个字符的字符串:123,234,3 去掉最后4个字符的字符串:123,234, 去掉最后5个字符的字符串:123,234
Description:
substr() function returns a part of a string. Syntax:
substr(string,start,length)
Parameter | Description |
---|---|
string | Required. Specifies a part of the string to be returned. |
start | Required. Specifies where in the string to begin.
|
length | Optional. Specifies the length of the string to be returned. The default is until the end of the string.
|
Return value: Returns the extracted part of the string, FALSE if failed, or an empty string.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the last few characters in php. For more information, please follow other related articles on the PHP Chinese website!