Tiny Dancer
Tiny Dancer

Reputation: 237

Remove last character from string if last character contain number in PHP

I have an array variable which contain values like this:

$items = array(
 "tbFrench",
 "eaItaly1",
 "discount21",
 "kkMM5",
 "NbndA",
 "fcMNSS334"
);

i nedd to remove last character of string from this array values if the last character contain number, for example:

$newItems = array();
foreach($items as $item){
  $newItems[] = $this->removeLastCharacter($item);
}
print_r($newItems);
....
function removeLastCharacter($string){
 // ????
}

i want the result to look like this when i print_r the $newItems variable:

Array ( [0] => tbFrench [1] => eaItaly [2] => discount2 [3] => kkMM [4] => NbndA [5] => fcMNSS33 )

Upvotes: 1

Views: 437

Answers (5)

Thanasis
Thanasis

Reputation: 439

There is a quick trick using rtrim.

$result =  rtrim($str,"0..9");

second argument is a range using 2 dots ".."

You are done !!!

Upvotes: 0

CD001
CD001

Reputation: 8472

You can do a RegEx replacement over all the items in an array by simply providing the array as the subject, like so:

$items = preg_replace('/^d$/', '', $items);

There's no need to put it into a function at all - print_r($items) outputs:

Array
(
    [0] => tbFrench
    [1] => eaItaly
    [2] => discount2
    [3] => kkMM
    [4] => NbndA
    [5] => fcMNSS33
)

If you want to replace all trailing digits you can use /^\d+$/

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 99001

Why not simply?

print_r( preg_replace( '/\d+$/', "", $items ) ); // preg_replace accepts an array as argument, pass yours directly, no need for a loop.

Array
(
    [0] => tbFrench
    [1] => eaItaly
    [2] => discount
    [3] => kkMM
    [4] => NbndA
    [5] => fcMNSS
)

Regex Explanation:

\d+ — matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
$ — asserts position at the end of a line

Upvotes: 0

shubhangee
shubhangee

Reputation: 539

Give a try with below code if it solve your problem

$items = array(
 "tbFrench",
 "eaItaly1",
 "discount21",
 "kkMM5",
 "NbndA",
 "fcMNSS334"
);

$newArr=array();
foreach($items as $item){
     $data = preg_replace('[\d$]','',$item);
     array_push($newArr,$data);
}

print_r($newArr);

Upvotes: 0

Benjamin Paap
Benjamin Paap

Reputation: 2759

You could use regular expressions to remove the last digit.

function removeLastCharacter($string){
    return preg_replace('[\d$]', '', $string);
}

\d matches every digit and $ references the end of the string. So this will only replace the last character if it is a digit at the end.

Upvotes: 2

Related Questions