在PHP中拆分字符串并获得最后一部分 [英] Splitting strings in PHP and get last part
问题描述
我需要在PHP中用-"分割字符串,然后获取最后一部分.
I need to split a string in PHP by "-" and get the last part.
因此,此:
abc-123-xyz-789
abc-123-xyz-789
我希望得到
"789"
"789"
这是我想出的代码:
substr(strrchr($urlId, '-'), 1)
工作正常,除了:
如果我的输入字符串不包含任何-",则必须从以下位置获取整个字符串:
If my input-string does not contain any "-", I must get the whole string, like from:
123
123
我需要回来
123
123
,它需要尽可能快. 感谢您的帮助!
and it needs to be as fast as possible. Any help is appreciated!
推荐答案
split($pattern,$string)
在给定的模式或正则表达式中拆分字符串(从5.3.0版本开始弃用)
split($pattern,$string)
split strings within a given pattern or regex (it's deprecated since 5.3.0)
preg_split($pattern,$string)
在给定的正则表达式模式下拆分字符串
preg_split($pattern,$string)
split strings within a given regex pattern
explode($pattern,$string)
在给定模式下分割字符串
explode($pattern,$string)
split strings within a given pattern
end($arr)
获取最后一个数组元素
end($arr)
get last array element
所以:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
将返回-
分隔字符串的最后一个元素.
Will return the last element of a -
separated string.
有一种方法可以做到这一点:
And there's a hardcore way to do this:
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
// | '--- get the last position of '-' and add 1(if don't substr will get '-' too)
// '----- get the last piece of string after the last occurrence of '-'
这篇关于在PHP中拆分字符串并获得最后一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!