【问题标题】:preg_match_all for words in and outside of bracketspreg_match_all 用于括号内和括号外的单词
【发布时间】:2014-10-30 14:02:22
【问题描述】:

我已经坐了几个小时来找出 php 中 preg_match_all 函数的正则表达式。 我的问题是我想从字符串中得到两个不同的东西。

假设你有字符串“代码很有趣[并且对大脑有好处。]但是[大脑]很累。”

我需要一个括号外的所有单词和括号中的文本作为一个字符串的数组。

类似的东西

[0] => Code
[1] => is
[2] => fun
[3] => and good for the brain.
[4] => But
[5] => the
[6] => brain is
[7] => tired.

帮助非常感谢。

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    你也可以试试下面的正则表达式,

    (?<=\[)[^\]]*|[.\w]+
    

    DEMO

    代码:

    <?php
    $data = "Code is fun [and good for the brain.] But the [brain is] tired.";
    $regex =  '~(?<=\[)[^\]]*|[.\w]+~';
    preg_match_all($regex, $data, $matches);
    print_r($matches);
    ?>
    

    输出:

    Array
    (
        [0] => Array
            (
                [0] => Code
                [1] => is
                [2] => fun
                [3] => and good for the brain.
                [4] => But
                [5] => the
                [6] => brain is
                [7] => tired.
            )
    
    )
    

    第一个查找绑定(?&lt;=\[)[^\]]* 匹配大括号[] 中存在的所有字符,第二个[.\w]+ 匹配剩余字符串中的一个或多个单词字符或点。

    【讨论】:

      【解决方案2】:

      您可以使用以下正则表达式:

      (?:\[([\w .!?]+)\]+|(\w+))
      

      正则表达式包含两种替换:一种用于匹配两个方括号内的所有内容,另一种用于捕获所有其他单词。

      这假定方括号内的部分不包含除字母、数字、_!.? 之外的任何字符。如果您需要添加更多标点符号,将它们添加到字符类应该很容易。

      如果您不想那个具体说明应该捕获什么,那么您可以使用否定字符类来代替 - 指定要匹配的而不是指定要匹配的内容。然后表达式变为:(?:\[([^\[\]]+)\]|(\w+))

      可视化:

      说明:

      (?:              # Begin non-capturing group
        \[             #   Match a literal '['
          (            #   Start capturing group 1
            [\w .!?]+  #     Match everything in between '[' and ']'
          )            #   End capturing group 1
        \]             #   Match literal ']'
        |              #  OR
        (              #   Begin capturing group 2
          \w+          #     Match rest of the words
        )              #   End capturing group 2
      )                # End non-capturing group
      

      Demo

      【讨论】:

      • 您可以使用分支重置来捕获 group1 中的匹配项:(?|[([\w .!?]+)]+|(\w+))
      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多