如何从php中删除/删除字符串中的最后一个字符

时间:2016-11-27 10:04:38

标签: php string character

如何从php字符串变量中动态删除最后一个字符。

$string = '10,20,30,';
echo $string;

可用输出:

10,20,30,

必填项:

10,20,30

5 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

rtrim($string, ",");删除字符串 end 的逗号。

PHP.net rtrim

trim($string, ",");删除字符串开头和结尾的逗号。

PHP.net trim

如果您正在使用数组,也可以使用implode:

PHP.net implode

来自php.net的例子:

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

答案 2 :(得分:0)

您可以使用

rtrim( $string, ',');

但我认为你的问题出在其他地方。好像你正在for / while / foreach循环中为这个字符串添加选项。

请改用:

$string = array[];
foreach ($parts as $part) {
  $string[] = $part;
}
$string = implode( $string, ',');

答案 3 :(得分:0)

是的!我已经得到了答案

$string = chop($string,",");

echo $string;

<强>输出

10,20,30

答案 4 :(得分:0)

如果PHP> 7.1,那么

$string[-1] = PHP_EOL;

DEMO