PHP在[[]]括号内获取字符串到数组

时间:2012-09-18 09:24:11

标签: php regex string

我正在用PHP写一些代码片段,

我有这种字符串变量

 $msg="Dear [[5]]
    We wish to continue the lesson with the [[6]]";

我需要从这个$ msg中获取5和6并分配给一个数组 ex array(5,6)

因为那些是片段编号,任何人都知道如何使用PHP

谢谢你的帮助

2 个答案:

答案 0 :(得分:4)

使用preg_match_all

$msg = "Dear [[5]] We wish to continue the lesson with the [[6]]";
preg_match_all("/\[\[(\d+)\]\]/", $msg, $matches);

如果匹配,$matches[1]将包含一个匹配数字的数组:

Array
(
    [0] => 5
    [1] => 6
)

<强> DEMO

答案 1 :(得分:1)

这是你想要的:

<?php

$msg = "Dear [[5]]
 We wish to continue the lesson with the [[6]]";

preg_match_all('/\[\[([0-9+])\]\]/', $msg, $array);

$array = $array[1];

print_r($array);

?>

输出:

Array
(
    [0] => 5
    [1] => 6
)