0LLiena
0LLiena

Reputation: 135

Erase part of string in php if same character until the end

Suppose I have a string as following:

11221211111212111111211111222222222

And what I want to obtain:

11221211111212111111211111

Basically, I just erased the last '2's since the "first one" of the last, if that makes any sense. I've considered running the string with a foreach but I'd like to check up for a code-friendlier alternative, in means of performance and readibility...

Upvotes: 0

Views: 53

Answers (2)

Sam
Sam

Reputation: 20486

The rtrim() method may be faster than using a regular expression, but you can match this expression and replace it with nothing:

(.)\1*$

That will capture any character ((.)) and then match 0+ more of that captured character (\1*) until the end of the string ($). Use this with PHP's preg_replace() like so:

$string = '11221211111212111111211111222222222';
$string = preg_replace('/(.)\1*$/', '', $string);

var_dump($string);
// string(26) "11221211111212111111211111"

Upvotes: 2

smistry
smistry

Reputation: 1126

$string = "11221211111212111111211111222222222";  
$newString = rtrim($string, substr($string, -1));
echo $newString;

Upvotes: 4

Related Questions