Home > Article > Backend Development > How to get or delete the last few characters in php
php can use the "substr($str,-N)" statement to get the last character. The parameter "N" specifies the number of characters to be read; to delete the last character, use "rtrim($str,"specified character" )" statement, you can also use the "substr($str,0,-N)" statement. The parameter "N" specifies the number of characters to be deleted.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php gets the last few characters
In PHP, you can use the substr() function to read the last few characters of a string.
The substr() function returns a part of a string. Just omit the third parameter of the function and set the second parameter to a negative value (-n), n specifies the last few characters you want to read
<?php header('content-type:text/html;charset=utf-8'); $str = "123456789"; echo "原字符串:".$str."<br>"; echo "读取后1个字符:".substr($str,-1)."<br>"; echo "读取后2个字符:".substr($str,-2)."<br>"; echo "读取后3个字符:".substr($str,-3)."<br>"; ?>
php delete the last few characters
1. Use the rtrim() function
rtrim() function can move Except whitespace characters or other predefined characters on the right side of the string.
<?php header('content-type:text/html;charset=utf-8'); $str = "123456789"; echo "原字符串:".$str."<br>"; echo "删除后1个字符:".rtrim($str,"9")."<br>"; echo "删除后2个字符:".rtrim($str,"89")."<br>"; echo "删除后3个字符:".rtrim($str,"789")."<br>"; ?>
2. Use the substr() function
The substr() function returns a part of the string. Just set the second parameter of the function to 0, and the third parameter to a negative value (-n), where n specifies the last few characters you want to delete.
<?php header('content-type:text/html;charset=utf-8'); $str = "123456789"; 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)."<br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get or delete the last few characters in php. For more information, please follow other related articles on the PHP Chinese website!