开发者

efficient string end replace

I would like to see if the ther开发者_运维百科e is a way to do this without preg_replace, just string functions.

I am using this

$str = "-41d3vUYHtK3D-GI3QXiVhvfR-zNooU7U_--2697";
preg_replace("/\-\d+$/i","",$str) 

to remove everything that follows and including the last "dash"


If it is not a requirement that the last characters have to be digits, then you can use substr [docs] and strrpos [docs]:

$str = substr($str, 0, strrpos($str, '-'));

Or in PHP 5.3.0, strstr [docs]:

$str = strstr($str, '-', true);

If, on the other hand, you want to remove the last dash and characters only if the following characters are digits, then using regular expressions would be the easier way.


$str = "-41d3vUYHtK3D-GI3QXiVhvfR-zNooU7U_--2697";

for($i=strlen($str)-1;$i>=0;$i--){
    if($str[$i] == '-'){
        $result = substr($str,0,$i);
        break;
    }

}
echo $result;

Returns -41d3vUYHtK3D-GI3QXiVhvfR-zNooU7U_-

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜