PHP正则表达式提取文本对象

时间:2011-12-14 02:44:54

标签: php regex arrays

我需要聚合一个对象数组。我假设使用RegEx来收集方括号包围的所有文本实例将是理想的方法。 (见下面的例子)。

有人可以解释我如何阅读文本以执行上述内容吗?

$links = some [[text]] here and another [[link]] here

因此$links[0]应该等于[[text]]

1 个答案:

答案 0 :(得分:3)

此模式将为您提供双括号内的文本作为内部分组,并包含外部括号,作为完整模式匹配:

$matches = array();
$links = "some [[text]] here and another [[link]] here";
preg_match_all("/\[\[([^\]]+)\]\]/", $links, $matches);
//---------------^^^^ Opening brackets [[ escaped
//-------------------^^^^^^^^ One or more characters excluding ] grouped in ()
//---------------------------^^^^ Closing brackets ]] escaped

var_dump($matches);
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "[[text]]"
    [1]=>
    string(8) "[[link]]"
  }
  [1]=>
  array(2) {
    [0]=>
    string(4) "text"
    [1]=>
    string(4) "link"
  }
}

所以你可以使用你需要的任何一个。

echo $matches[0][1];
// [[link]]
echo $matches[1][1];
// link
相关问题