正则表达式,如何将内容文本转换为数组?

时间:2012-09-28 04:52:37

标签: php arrays preg-match-all

[code]
 [1] text 1
 [2] text 2
 [3] text 3
[/code]

所以我需要值text 1, text 2, text 3为数组。

我的麻烦:

$matches = preg_match_all( "/^\[\d{1,3}\](.*)/", $content, $tags );

它返回一个空值的数组:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

)
1

如何修复或改善它?

[code]
 [1] text 1
 Different content here
 [2] text 2 Another dif..
 [3] Also something either
  to be continues!
[/code]

使用多行时,它只返回text 1而不是数组第一个元素中的所有代码

Array
(
    [0] => Array
        (
            [0] => [1] text 1


            [1] => [2] text 2 Another dif..

            [2] => [3] Also something either

        )

    [1] => Array
        (
            [0] =>  text 1


            [1] =>  text 2 Another dif..

            [2] =>  Also something either

        )

)
1

其他元素也只有第一个字符串结果。

1 个答案:

答案 0 :(得分:4)

您应该删除锚点^并将(.*)更改为预测集([^[]*)

$s =<<<EOM
[code]
 [1] text 1
 Another line
 [2] text 2
 And another line too
 [3] text 3
[/code]
EOM;

preg_match_all("/\[\d{1,3}\]([^[]*)/", $s, $tags);

print_r($tags);