使用基于正则表达式的解决方案将比其他方法更慢/效率更低。
如果您正在考虑“更简单”意味着“更少的函数调用,那么我会推荐preg_split()
or preg_match_all()
。不过,我想解释一下,它preg_match_all()
会在全局范围内添加一个变量,而preg_split()
不必这样做。另外,preg_match_all()
生成一个多维数组,你只需要一个 1-dim 数组 - 这是preg_split()
.
这是一系列选项。有些是我的,有些是别人发的。有些工作,有些工作比其他工作更好,有些不工作。教育时间到了...
$stuff = "[1379082600-1379082720],[1379082480-1379082480],[1379514420-1379515800],";
// NOTICE THE TRAILING COMMA ON THE STRING!
// my preg_split() pattern #1 (72 steps):
var_export(preg_split('/[\],[]+/', $stuff, 0, PREG_SPLIT_NO_EMPTY));
// my preg_split() pattern #2 (72 steps):
var_export(preg_split('/[^\d-]+/', $stuff, 0, PREG_SPLIT_NO_EMPTY));
// my preg_match_all pattern #1 (16 steps):
var_export(preg_match_all('/[\d-]+/', $stuff, $matches) ? $matches[0] : 'failed');
// my preg_match_all pattern #2 (16 steps):
var_export(preg_match_all('/[^\],[]+/', $stuff, $matches) ? $matches[0] : 'failed');
// Bora's preg_match_all pattern (144 steps):
var_export(preg_match_all('/\[(.*?)\]/', $stuff, $matches) ? $matches[0] : 'failed');
// Alex Howansky's is the cleanest, efficient / correct method
var_export(explode('],[', trim($stuff, '[],')));
// Andy Gee's method (flawed / incorrect -- 4 elements in output)
var_export(explode(",", str_replace(["[","]"], "", $stuff)));
// OP's method (flawed / incorrect -- 4 elements in output)
$stuff = str_replace(["[", "]"], ["", ""], $stuff);
$stuff = explode(",", $stuff);
var_export($stuff);
如果您想查看方法演示,请单击此处。
如果您想查看步数,请单击此模式演示并交换我提供的模式。