Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove repeated character at the end of string in PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading