【问题标题】:php preg_match_all not workingphp preg_match_all 不起作用
【发布时间】:2017-10-19 01:25:09
【问题描述】:

正则表达式会突出显示错误的词,例如 Hell«o»,而忽略正确的词 «Hello»Hello, 所以,我的问题对于我的 javascript 代码来说工作得很好,但是当我为 php 尝试它时,它也会突出显示字符串,这不应该:

  1. '«这是销售点»';

这是我的正则表达式:https://regex101.com/r/SqCR1y/14

PHP 代码:

$re = '/^(?:.*[[{(«][^\]})»\n]*|[^[{(«\n]*[\]})»].*|.*\w[[{(«].*|.*[\]})»]\w.*)$/m';
$str = '«This is the point of sale»';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

//输出

array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(29) "«This is the point of sale»"
  }
}

预期:空数组

jsfiddle 在这里,工作正常

提前致谢

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    您没有使用正确的模式。试试这个:

    $re = '/^
      (?:
        \([^)\n] | [^(\n]*\). |
        \[[^]\n] | [^[\n]*\]. |
        {[^}\n] | [^{\n]}.* |
        «[^»\n] | [^«\n]*». |
        .?\w[[{(«]. | .?[\]})»]\w.
      )
    $/mxu';
    

    【讨论】:

      【解决方案2】:

      像 "(not)balanced)" 这样的字符串呢?这应该合法吗?

      这种类型的模式在您的测试输入中并不明确,但由于您的“好”字符串都不是不平衡的,您可以考虑通过使用 regex recursion 匹配平衡括号表达式并定位 valid 来覆盖这些情况 字符串而不是无效的:

      $re = '/
          ^
          (?!.*\w[{}«»\(\)\[\]]\w)  //disallow brackets inside words
          (?:
          [^\n{}«»\(\)\[\]]|      //non bracket character, OR:
          (                       //(capture group #1, the recursive subpattern) "one of the following balanced groups":
          (\((?:(?>[^\n«»\(\){}\[\]]|(?1))*)\))|  //balanced paren groups
          (\[(?:(?>[^\n«»\(\){}\[\]]|(?1))*)\])|  //balanced bracket groups
          («(?:(?>[^\n«»\(\){}\[\]]|(?1))*)»)|        //balanced chevron groups
          ({(?:(?>[^\n«»\(\){}\[\]]|(?1))*)})     //balanced curly bracket groups
          )
          )+ //repeat "non bracket character or balanced group" until end of string
          $  
      /mxu';
      

      递归采用这种形式:

      [openbracket]([nonbracket] | [open/close pattern again via recursion])*[closebracket]
      

      要递归使用模式的一部分,您可以通过包含它的捕获组(?N) 来识别它,其中 N 是组的编号。

      *在进入递归内容之前,初始的否定前瞻将失败任何“字边界”违规

      *此正则表达式看起来比原始方法快 35%,如下所示:https://regex101.com/r/MBITHe/4

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-12
        • 1970-01-01
        相关资源
        最近更新 更多