I would like to remove the last number including the dash from this string:
hello-world-093
the result should be:
hello-world
http://php.net/manual/en/function.preg-replace.php
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] );
in your case it should be something like :
$subject = 'hello-world-093' ;
$subject_stripped = preg_replace ( '/-[0-9]*$/' , '' , $subject);
The above pattern will delete the -
and all numbers that follow at the end of the string.
http://php.net/manual/en/function.strrpos.php
strrpos — Find the position of the last occurrence of a substring in a string
Do strrpos
with the character -
and you know that the result will be the last position of a -
in the string.
Now, you can get only the first portion of the string by using http://www.php.net/manual/en/function.substr.php and supplying your position as the length.
Here is another way. I offer this not as the best way way but just another way to skin a cat. I think it's important to understand there are many ways to solve a problem and to explore them. You'll learn a lot by learning to tackle a problem from different angles.
Good luck hope this helps,
Tim Dumas
Tim@mpact-media.com
<?php
$pattern = "/^(.*)-[0-9]*$/";
$string = "hello-world-093";
preg_match($pattern, $string, $matches);
print_r($matches);
?>