php去掉字符串末尾字符
方法1:使用substr()函数
直接使用substr()函数倒序裁掉最后一位字符
<?php
header('content-type:text/html;charset=utf-8');
$str = '123,234,345,';
echo "原字符串:",$str,'<br/>';
echo "去掉末尾字符的字符串:",substr($str,0,-1);
?>
输出:
原字符串:123,234,345, 去掉末尾字符的字符串:123,234,345
说明:
substr() 函数返回字符串的一部分。语法:
substr(string,start,length)

方法2:使用rtrim()函数
rtrim() 函数移除字符串右侧的空白字符或其他预定义字符。
1、指定末尾字符
<?php
header('content-type:text/html;charset=utf-8');
$str = '123,234,345,';
echo "原字符串:",$str,'<br/>';
echo "去掉末尾字符的字符串:",rtrim($str,',');
?>
输出:
原字符串:123,234,345, 去掉末尾字符的字符串:123,234,345
2、不知道末尾字符
<?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);
?>
输出:
原字符串:123,234,345,1 去掉末尾字符的字符串:123,234,345,

