Reputation: 1618
i am trying to Check if last value after the dash (-) is a number in a string in PHP, if its a number then remove the value from last dash (-).
Here is how my string looks like:
about-us-1
or it might looks like about-us-new
but i just want to trim only about-us-1
because it have a numeric value in last after dash.
And here is how my PHP function looks like:
public static function checkSlug($modelName, $id, $inputSlug = null){
$i =1;
$rows = self::getAllRow($modelName, $id);
foreach($rows as $row){
if($inputSlug == $row['slug']){
$inputSlug = $inputSlug."-".$i;
$i++;
}
}
return $inputSlug;
}
What it currently do is it adds a new number after -
like this about-us-1-2
Looking for short and simple technique to fix this.
Thank you!
Upvotes: 2
Views: 1164
Reputation: 23958
Use preg_replace()
<?php
$string = 'about-us-1';
$string = preg_replace('/-[0-9]*$/', '', $string);
echo $string; // about-us
?>
Upvotes: 1
Reputation: 785651
You can change this line:
$inputSlug = $inputSlug."-".$i;
to this:
$inputSlug = preg_replace('/-\d+$/', '', $inputSlug) . "-" . $i;
preg_replace('/-\d+$/', '', $inputSlug)
will remove hyphen and trailing digits from input string if present.
Upvotes: 2