To satisfy the requirement that βit should be as fast as possibleβ, I conducted a comparative analysis of some possible solutions. Each solution had to satisfy this set of tests.
$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 decision has been executed 1,000,000 times in test cases:
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%
Turns out the fastest of them was using substr with strpos . Note that in this solution, we must check strpos for false so that we can return the full string (satisfying the zzz case).
source share