Home > Back-end >  Remove repeated character at the end of string in PHP
Remove repeated character at the end of string in PHP

Time:11-17

I have a string that is being dynamically created. As a result, sometimes the end of the string might have one dash or sometimes it might have more. I don't know how many dashes will be at the end; however, no matter how many dashes are at the end, I need to drop them all. So a few examples:

This: 101-239204-9230--- Becomes: 101-239204-9230

This: 101-239204-9230- Becomes: 101-239204-9230

So no matter how many dashes at the end, if there are dashes at the end, I need to drop them all. I just can't wrap my head around how to do this exactly.

I've tried using str_replace, which works if I know the exact number of dashes, so:

$number = 101-239204-9230---
$fixedNumber = str_replace('---', '', $number);
echo $fixedNumber

Again, the problem here is that I don't know how many dashes will be at the end.

CodePudding user response:

To remove fixed character at the end of string (in this case -), try:

$number = "101-239204-9230---";
echo rtrim($number, '-');

Documentation: rtrim - Strip whitespace (or other characters) from the end of a string

CodePudding user response:

Solution use:

$number = '101-239204-9230---';
$fixedNumber = rtrim($number,'-');
echo $fixedNumber;

Maybe helpfull: https://www.php.net/manual/en/ref.strings.php

  • Related