0

For example, if I have this string:

$stuff = "[1379082600-1379082720],[1379082480-1379082480],[1379514420-1379515800],";

I know can do this to split it into an array like this:

$stuff = str_replace(array("[","]"),array("",""),$stuff);
$stuff = explode(",",$stuff);

But it seems like there would be an easier way since the string is already in an array form almost. Is there an easier way?

4

5 回答 5

3

因为字符串几乎已经是数组形式了。

它不是。就编程语言而言,字符串和数组是完全不同的东西。

有没有更简单的方法?

寻找“更简单的方法”毫无意义。你现在的方式已经很容易了。

于 2013-09-13T14:59:19.667 回答
1

You can get inside [] with preg_match_all. Try following:

preg_match_all("/\[(.*?)\]/",$stuff, $matches);

Output of $matches[1]

array (size=3)
  0 => string '1379082600-1379082720' (length=21)
  1 => string '1379082480-1379082480' (length=21)
  2 => string '1379514420-1379515800' (length=21)
于 2013-09-13T15:17:58.957 回答
1

修剪前导和尾随字符,然后吐在],[

$stuff = explode('],[', trim($stuff, '[],');
于 2013-09-13T14:56:30.440 回答
0

这和我想的一样好

$stuff = array_filter(explode(",",str_replace(array("[","]"),"",$stuff)));

print_r($stuff);


    [0] => 1379082600-1379082720
    [1] => 1379082480-1379082480
    [2] => 1379514420-1379515800
于 2013-09-13T14:55:28.667 回答
0

使用基于正则表达式的解决方案将比其他方法更慢/效率更低。

如果您正在考虑“更简单”意味着“更少的函数调用,那么我会推荐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);

如果您想查看方法演示,请单击此处

如果您想查看步数,请单击此模式演示并交换我提供的模式。

于 2017-08-04T00:47:59.177 回答