W3docs

Remove trailing delimiting character from a delimited string

To remove the trailing delimiter from a delimited string in PHP, you can use the rtrim function.

To remove the trailing delimiter from a delimited string in PHP, you can use the rtrim function. This function removes characters from the right side of a string.

For example, consider the following string:

A PHP string

$string = "apple,banana,orange,";

To remove the trailing comma from this string, you can use the following code:

How to remove the trailing delimiter from a delimited string in PHP?

<?php

$string = "apple,banana,orange,";
echo $string = rtrim($string, ",");

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will remove the trailing comma from the string, resulting in the following string:


"apple,banana,orange"

You can also use the rtrim function to remove multiple characters from the right side of a string. For example, to remove both the comma and the space from the end of the string, you can use the following code:

How to remove the trailing delimiter from a delimited string using rtrim() function to remove multiple characters in PHP?

<?php

$string = "apple,banana,orange,";
echo $string = rtrim($string, ", ");

You can also use the substr function to remove the last character from a string. For example, to remove the last character from the string, you can use the following code:

How to remove the trailing delimiter from a delimited string using substr() function in PHP?

<?php

$string = "apple,banana,orange,";
echo $string = substr($string, 0, -1);

This will remove the last character from the string, resulting in the same string as before:


"apple,banana,orange"