简体   繁体   中英

How to eliminate/remove last character from a string in php

How i can remove last character dynamically from a php string variable.

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

Available Output:

10,20,30,

Required Output:

10,20,30

rtrim($string, ","); removes comma at the end of the string.

PHP.net rtrim

trim($string, ","); removes comma at the beginning and end of a string.

PHP.net trim

You can also use implode if you're working with arrays :

PHP.net implode

Example from 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) ""

?>

You could use

rtrim( $string, ',');

But I think your problem lies elsewhere. Seems like you are adding options to this string in a for/while/foreach loop.

Use this instead:

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

Yes ! I have gotten answer

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

echo $string;

Output

10,20,30

If PHP > 7.1 then

$string[-1] = PHP_EOL;

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM