只是一个想法:
function explode_reversed($delim,$s){
$result = array();
$w = "";
$l = 0;
for ($i = strlen($s)-1; $i>=0; $i-- ):
if ( $s[$i] == "$delim" ):
$l++;
$w = "";
else:
$w = $s[$i].$w;
endif;
$result[$l] = $w;
endfor;
return $result;
}
$arr = explode_reversed(" ","Hello! My name is John.");
print_r($arr);
结果:
Array
(
[0] => John.
[1] => is
[2] => name
[3] => My
[4] => Hello!
)
但这比爆炸要慢得多。做了一个测试:
$start_time = microtime(true);
for ($i=0; $i<1000;$i++)
$arr = explode_reversed(" ","Hello! My name is John.");
$time_elapsed_secs = microtime(true) - $start_time;
echo "time: $time_elapsed_secs s<br>";
耗时 0.0625 - 0.078125s
但
for ($i=0; $i<1000;$i++)
$arr = explode(" ","Hello! My name is John.");
仅需 0.015625 秒
最快的解决方案似乎是:
array_reverse(explode($your_delimiter, $your_string));
在 1000 次循环中,这是我能得到 0.03125 秒的最佳时间。