Home >Backend Development >PHP Problem >How to remove characters at the end of string in php
php method to remove the characters at the end of the string: 1. Directly use the substr() function to trim the last character in reverse order, the syntax is "substr(string,0,-1)"; 2. Use rtrim() Function, syntax "rtrim(string,charlist)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php removes strings The last character
Method 1: Use the substr() function
Use the substr() function directly to cut off the last character in reverse order
<?php header('content-type:text/html;charset=utf-8'); $str = '123,234,345,'; echo "原字符串:",$str,'<br/>'; echo "去掉末尾字符的字符串:",substr($str,0,-1); ?>
Output:
原字符串:123,234,345, 去掉末尾字符的字符串:123,234,345
Description:
substr() function returns a part of a string. Syntax:
substr(string,start,length)
Method 2: Use the rtrim() function
rtrim() function removes the right side of the string whitespace characters or other predefined characters on the side.
1. Specify the last character
<?php header('content-type:text/html;charset=utf-8'); $str = '123,234,345,'; echo "原字符串:",$str,'<br/>'; echo "去掉末尾字符的字符串:",rtrim($str,','); ?>
Output:
原字符串:123,234,345, 去掉末尾字符的字符串:123,234,345
2. Don’t know the last character
<?php header('content-type:text/html;charset=utf-8'); $str = '123,234,345,1'; echo "原字符串:",$str,'<br/>'; //不知道末尾字符,需先获取末字符 $last_char=$str{strlen($str)-1}; echo "去掉末尾字符的字符串:",rtrim($str,$last_char); ?>
Output:
原字符串:123,234,345,1 去掉末尾字符的字符串:123,234,345,
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove characters at the end of string in php. For more information, please follow other related articles on the PHP Chinese website!