仅按最后一个分隔符分解

php
2022-08-30 11:34:10

有没有办法使用分解函数仅按最后一次分隔符发生来分解?

$string = "one_two_  ... _three_four";

$explodeResultArray = explode("_", $string);

结果应该是:

echo $explodeResultArray[0]; // "one_two_three ...";
echo $explodeResultArray[1]; // "four";

答案 1

简单:

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

正则表达式:

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

字符串反转:

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

答案 2

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

$string = "one_two_three_four";
$part   = implode('_', explode('_', $string, -1));
echo $part;

结果是

one_two_three

推荐