【问题标题】:PHP regular expressions extract text objectsPHP正则表达式提取文本对象
【发布时间】:2011-12-14 02:44:54
【问题描述】:

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

有人可以解释一下我将如何阅读文本来执行上述操作吗?

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

所以$links[0] 应该等于[[text]]

【问题讨论】:

    标签: php regex arrays


    【解决方案1】:

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

    $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
    

    【讨论】:

    • 谢谢,我喜欢它的简单性,并且也能够获得括号内的值!我是 RegEx 的新手,但在我目前的工作中开始真正需要它们。欢呼
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2017-10-08
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多