在 PHP 中拆分字符串并获取最后一部分


Splitting strings in PHP and get the last part

我需要在 PHP 中用"-"拆分一个字符串并得到最后一部分。

所以从这个:

ABC-123-XYZ-789

我希望得到

"789">

这是我想出的代码:

substr(strrchr($urlId, '-'), 1)

工作正常,除了:

如果我的输入字符串不包含任何"-",我必须获取整个字符串,例如:

123

我需要回来

123

它需要尽可能快。

  • preg_split($pattern,$string)给定正则表达式模式中的拆分字符串
  • explode($pattern,$string)给定模式中拆分字符串
  • end($arr)获取最后一个数组元素

所以:

$strArray = explode('-',$str)
$lastElement = end(explode('-', $strArray));
// or
$lastElement = end(preg_split('/-/', $str));

将返回-分隔字符串的最后一个元素。

<小时 />

有一个硬核方法可以做到这一点:

$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 '-'
$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);

这没有E_STRICT问题。

只需检查分隔字符是否存在,然后拆分或不拆分:

if (strpos($potentiallyDelimitedString, '-') !== FALSE) {
  found delimiter, so split
}

为了满足"它需要尽可能快">的要求,我针对一些可能的解决方案运行了一个基准测试。每个解决方案都必须满足这组测试用例。

$cases = [
    'aaa-zzz'                     => 'zzz',
    'zzz'                         => 'zzz',
    '-zzz'                        => 'zzz',
    'aaa-'                        => '',
    ''                            => '',
    'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz',
];

以下是解决方案:

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);
}

下面是针对测试用例运行每个解决方案 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%

所以事实证明,其中最快的是将substrstrpos一起使用。请注意,在此解决方案中,我们必须检查strpos是否有false,以便我们可以返回完整的字符串(满足zzz情况(。

array_reverse(explode('-', $str))[0]

这段代码将做到这一点

<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>

根据这篇文章:

end((explode('-', $string)));

这不会在 PHP 5(PHP 魔术(中引起E_STRICT警告。尽管警告将在 PHP 7 中发出,因此在其前面添加@可以用作解决方法。

正如其他人所提到的,如果您不将explode()的结果分配给变量,则会收到以下消息:

E_STRICT:严格的标准:只有变量应该通过引用传递

正确的方法是:

$words = explode('-', 'hello-world-123');
$id = array_pop($words); // 123
$slug = implode('-', $words); // hello-world

由于explode()返回一个数组,如果您碰巧知道最后一个数组项的位置,则可以直接在该函数的末尾添加方括号。

$email = 'name@example.com';
$provider = explode('@', $email)[1];
echo $provider; // example.com

或者另一种方式是list()

$email = 'name@example.com';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com

如果您不知道职位:

$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four

接受的答案中有一个错误,如果找不到分隔符,它仍然会吃输入字符串的第一个字符。

$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);

产生预期结果:5

$str = '1-2-3-4-5';
echo substr($str, strrpos($str, ';') + 1);

产生-2-3-4-5

$str = '1-2-3-4-5';
if (($pos = strrpos($str, ';')) !== false)
    echo substr($str, $pos + 1);
else
    echo $str;

根据需要生成整个字符串。

3v4l 链接

此解决方案是空安全的,支持所有 PHP 版本:

// https://www.php.net/manual/en/function.array-slice.php
$strLastStringToken = array_slice(explode('-',$str),-1,1)[0];

如果$str = null返回''

对我来说的硬核方式:

  $last = explode('-',$urlId)[count(explode('-',$urlId))-1];
你可以

这样做:

$str = "abc-123-xyz-789";
$last = array_pop( explode('-', $str) );
echo $last; //echoes 789

您可以将array_popexplosion 结合使用

法典:

$string = 'abc-123-xyz-789';
$output = array_pop(explode("-",$string));
echo $output;

演示:点击这里

你可以

这样做:

$str = "abc-123-xyz-789";
$arr = explode('-', $str);
$last = array_pop( $arr );
echo $last; //echoes 789

只需调用以下一行代码:

 $expectedString = end(explode('-', $orignalString));