我需要在PHP中用" - "拆分字符串并获取最后一部分.
所以从这个:
ABC-123-XYZ-789
我希望得到
"789"
这是我提出的代码:
substr(strrchr($urlId, '-'), 1)
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,除了:
如果我的输入字符串不包含任何" - ",我必须得到整个字符串,如:
123
我需要回来
123
它需要尽可能快.任何帮助表示赞赏!
Wes*_*óes 107
split($pattern,$string)在给定模式或正则表达式中拆分字符串(自5.3.0以来不推荐使用)
preg_split($pattern,$string) 在给定的正则表达式模式中拆分字符串
explode($pattern,$string) 在给定模式中拆分字符串
end($arr) 获取最后一个数组元素
所以:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
将返回$lastElement = end($strArray)分隔字符串的最后一个元素.
还有一种硬核方法可以做到这一点:
$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 '-'
Run Code Online (Sandbox Code Playgroud)
Dal*_*ale 20
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);
Run Code Online (Sandbox Code Playgroud)
编辑::最后解决了删除E_STRICT问题
只需检查分隔字符是否存在,并分割或不分割:
if (strpos($potentiallyDelimitedString, '-') !== FALSE) {
found delimiter, so split
}
Run Code Online (Sandbox Code Playgroud)
为了满足“需要尽可能快”的要求,我针对一些可能的解决方案进行了基准测试。每个解决方案都必须满足这组测试用例。
$cases = [
'aaa-zzz' => 'zzz',
'zzz' => 'zzz',
'-zzz' => 'zzz',
'aaa-' => '',
'' => '',
'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz',
];
Run Code Online (Sandbox Code Playgroud)
以下是解决方案:
function test_substr($str, $delimiter = '-') {
$idx = strrpos($str, $delimiter);
return $idx === false ? $str : substr($str, $idx + 1);
}
function test_end_index($str, $delimiter = '-') {
$arr = explode($delimiter, $str);
return $arr[count($arr) - 1];
}
function test_end_explode($str, $delimiter = '-') {
$arr = explode($delimiter, $str);
return end($arr);
}
function test_end_preg_split($str, $pattern = '/-/') {
$arr = preg_split($pattern, $str);
return end($arr);
}
Run Code Online (Sandbox Code Playgroud)
以下是每个解决方案针对测试用例运行 1,000,000 次后的结果:
test_substr : 1.706 sec
test_end_index : 2.131 sec +0.425 sec +25%
test_end_explode : 2.199 sec +0.493 sec +29%
test_end_preg_split : 2.775 sec +1.069 sec +63%
Run Code Online (Sandbox Code Playgroud)
事实证明,其中最快的是使用substrwith strpos。请注意,在此解决方案中,我们必须进行检查,strpos以便false我们可以返回完整的字符串(适合这种zzz情况)。
| 归档时间: |
|
| 查看次数: |
97216 次 |
| 最近记录: |