4

I would like to remove the last number including the dash from this string:

hello-world-093

the result should be:

hello-world

4

3 に答える 3

5

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.

于 2013-03-05T00:12:39.083 に答える
1

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.

于 2013-03-05T00:02:24.703 に答える
0

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);
?>
于 2013-03-05T00:24:27.507 に答える