仅按最后一个分隔符进行爆炸

Far*_*mov 31 php

有没有办法使用爆炸功能只能通过最后的分隔符出现爆炸?

$string = "one_two_  ... _three_four";

$explodeResultArray = explode("_", $string);
Run Code Online (Sandbox Code Playgroud)

结果应该是:

$expoldeResultArray[0] is "one_two_three ...";

$expoldeResultArray[1] is "four";
Run Code Online (Sandbox Code Playgroud)

sou*_*rge 74

直截了当:

$parts = explode('_', $string);
$last = array_pop($parts);
$parts = array(implode('_', $parts), $last);
echo $parts[0]; // outputs "one_two_three"
Run Code Online (Sandbox Code Playgroud)

常用表达:

$parts = preg_split('~_(?=[^_]*$)~', $string);
echo $parts[0]; // outputs "one_two_three"
Run Code Online (Sandbox Code Playgroud)

字符串反转:

$reversedParts = explode('_', strrev($string), 2);
echo strrev($reversedParts[0]); // outputs "four"
Run Code Online (Sandbox Code Playgroud)

  • @MichaelCoxon但是使用utf-8字符串会很痛苦. (4认同)

nib*_*bra 36

无需解决方法.explode()接受负限制.

$string = "one_two_three_four";
$part   = implode('_', explode('_', $string, -1));
echo $part;
Run Code Online (Sandbox Code Playgroud)

结果是

one_two_three
Run Code Online (Sandbox Code Playgroud)

  • 但是四在哪里? (7认同)

小智 9

您可以执行以下操作:

$string = "one_two_three_four";
$explode = explode('_', $string); // split all parts

$end = '';
$begin = '';

if(count($explode) > 0){
    $end = array_pop($explode); // removes the last element, and returns it

    if(count($explode) > 0){
        $begin = implode('_', $explode); // glue the remaining pieces back together
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:array_shift应该是array_pop


Use*_*ern 9

我选择使用substring,因为你想要一个特定点的字符串:

$string = "one_two_three_four_five_six_seven";
$part1 = substr("$string",0, strrpos($string,'_'));
$part2 = substr("$string", (strrpos($string,'_') + 1));
var_dump($part1,$part2);
Run Code Online (Sandbox Code Playgroud)

结果:

string(27) "one_two_three_four_five_six"
string(5) "seven"
Run Code Online (Sandbox Code Playgroud)


mcr*_*ley 5

<?php
$lastPos = strrpos($string, '_');
if ($lastPos !== false) {
    $start = substr($string, 0, $lastPos);
    $end = substr($string, $lastPos+1);
} else {
    // no delimeter found!
}
Run Code Online (Sandbox Code Playgroud)

如果你只关心最后一部分,那就更简单了。

<?php
$end = substr(strrchr($string, '_'), 1);
Run Code Online (Sandbox Code Playgroud)