在 PHP 中拆分字符串并获得最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17030779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting strings in PHP and get last part
提问by Raphael Jeger
I need to split a string in PHP by "-" and get the last part.
我需要在 PHP 中用“-”分割一个字符串并得到最后一部分。
So from this:
所以从这个:
abc-123-xyz-789
abc-123-xyz-789
I expect to get
我希望得到
"789"
“789”
This is the code I've come up with:
这是我想出的代码:
substr(strrchr($urlId, '-'), 1)
which works fine, except:
工作正常,除了:
If my input-string does not contain any "-", I must get the whole string, like from:
如果我的输入字符串不包含任何“-”,我必须获取整个字符串,例如:
123
123
I need to get back
我需要回来
123
123
and it needs to be as fast as possible. Any help is appreciated!
它需要尽可能快。任何帮助表示赞赏!
回答by Wesley Schleumer de Góes
split($pattern,$string)
split strings within a given pattern or regex (it's deprecated since 5.3.0)
split($pattern,$string)
在给定的模式或正则表达式中拆分字符串(自 5.3.0 起已弃用)
preg_split($pattern,$string)
split strings within a given regex pattern
preg_split($pattern,$string)
在给定的正则表达式模式中拆分字符串
explode($pattern,$string)
split strings within a given pattern
explode($pattern,$string)
在给定模式中拆分字符串
end($arr)
get last array element
end($arr)
获取最后一个数组元素
So:
所以:
end(split('-',$str))
end(split('-',$str))
end(preg_split('/-/',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
$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 '-'
回答by Dale
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);
EDIT::Finally got around to removing the E_STRICT issue
编辑::终于解决了 E_STRICT 问题
回答by Grant Thomas
Just check whether or not the delimiting character exists, and either split or don't:
只需检查分隔字符是否存在,然后拆分或不拆分:
if (strpos($potentiallyDelimitedString, '-') !== FALSE) {
found delimiter, so split
}
回答by Infinity
This code will do that
这段代码会做到这一点
<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>
回答by rybo111
As has been mentioned by others, if you don't assign the result of explode()
to a variable, you get the message:
正如其他人所提到的,如果您不将结果分配给explode()
变量,则会收到以下消息:
E_STRICT: Strict standards: Only variables should be passed by reference
E_STRICT:严格的标准:只有变量应该通过引用传递
The correct way is:
正确的方法是:
$words = explode('-', 'hello-world-123');
$id = array_pop($words); // 123
$slug = implode('-', $words); // hello-world
回答by Luke Baulch
To satisfy the requirement that "it needs to be as fast as possible"I ran a benchmark against some possible solutions. Each solution had to satisfy this set of test cases.
为了满足“它需要尽可能快”的要求,我针对一些可能的解决方案运行了一个基准测试。每个解决方案都必须满足这组测试用例。
$cases = [
'aaa-zzz' => 'zzz',
'zzz' => 'zzz',
'-zzz' => 'zzz',
'aaa-' => '',
'' => '',
'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz',
];
Here are the solutions:
以下是解决方案:
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);
}
Here are the results after each solution was run against the test cases 1,000,000 times:
以下是针对测试用例运行每个解决方案 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%
So turns out the fastest of these was using substr
with strpos
. Note that in this solution we must check strpos
for false
so we can return the full string (catering for the zzz
case).
所以事实证明,其中最快的是使用substr
with strpos
。请注意,在此解决方案中,我们必须进行检查strpos
,false
以便我们可以返回完整的字符串(针对这种zzz
情况)。
回答by kenorb
As per this post:
根据这篇文章:
end((explode('-', $string)));
which won't cause E_STRICTwarning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @
in front of it can be used as a workaround.
这不会在 PHP 5 ( PHP magic) 中引起E_STRICT警告。虽然警告会在 PHP 7 中发出,所以在它前面添加可以作为一种解决方法。@
回答by rybo111
Since explode()
returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.
由于explode()
返回一个数组,如果您碰巧知道最后一个数组项的位置,则可以直接在该函数的末尾添加方括号。
$email = '[email protected]';
$provider = explode('@', $email)[1];
echo $provider; // example.com
Or another way is list()
:
或者另一种方式是list()
:
$email = '[email protected]';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com
If you don't know the position:
如果你不知道职位:
$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four
回答by Nelson
You can do it like this:
你可以这样做:
$str = "abc-123-xyz-789";
$last = array_pop( explode('-', $str) );
echo $last; //echoes 789
回答by Ali
You can use array_popcombined with explode
您可以将array_pop与爆炸结合使用
Code:
代码:
$string = 'abc-123-xyz-789';
$output = array_pop(explode("-",$string));
echo $output;
DEMO: Click here
演示:点击这里