【问题标题】:How to match the regex pattern of [...]如何匹配 [...] 的正则表达式模式
【发布时间】:2014-08-13 08:13:25
【问题描述】:

我正在使用 wordpress,我需要过滤掉此模式中的所有字符串

[gallery columns............] 

例如,如果这样的字符串

[gallery columns="3" ids="426,425,427"] abc asdasdsad

它应该返回,注意]和下一个字符串的第一个字符之间的空格也应该被删除(如果有的话)

abc asdasdsad

感谢您的帮助,尝试了一些像 ([\[\s\S\] ]) 这样的正则表达式,但不起作用。

【问题讨论】:

  • 您要匹配abc asdasdsad[gallery columns="3" ids="426,425,427"]
  • want go get abc asdasdsad, [gallery columns="3" ids="426,425,427"] 是我需要过滤掉的,例如preg_replace()...

标签: php html regex


【解决方案1】:

使用模式:

/\[.*?\]\s*/

确切的说法是使用preg_replace:

preg_replace( "/\[.*?\]\s*/", "", $str );

【讨论】:

    【解决方案2】:

    另一种解决方案。 不是正则表达式,但更有趣。 使用 stringpos 的组合,带有 substr 和 trim :)

    <?
    $string = '[gallery columns="3" ids="426,425,427"] abc asdasdsad';
    $pos = strrpos($string, "]");
    
    if ($pos === false) {
      echo "Could not find ']' in string '$string'";
    }
    else {
      // Grab what you want from the next char position onwards
      $wanted = substr($string, $pos+1);
    
      // Get rid of starting and end spaces
      trim($wanted);
    
      // Print out result
      echo "RESULT: $wanted";
    }
    ?>
    

    【讨论】:

    • trim( substr($string, $pos+1) );
    • 好地方。预计在重构时会这样做。但是为了用评论解释解决方案,选择了更详细的路径:)
    【解决方案3】:

    使用strip_shortcodes,它在 WordPress 中可用,它将处理任何和所有类型的 WordPress 短代码的任何和所有边缘情况。

    【讨论】:

    • 这是一个更优雅的分辨率,之前没有注意到wordpress已经有这个功能,谢谢
    【解决方案4】:

    如果你只对[...]感兴趣,那么试试

    \[[\s\S]+\]
    

    这里是online demo


    从索引 1 和 2 中获取匹配组以匹配两者

    (\[[\s\S]+\])\s*(.*)
    

    这里是online demo


    您也可以使用[^\]]+ 代替[\s\S]+

    示例代码:

    $re = "/(\\[[^\\]]+\\])\\s*(.*)/";
    $str = "[gallery columns=\"3\" ids=\"426,425,427\"] abc asdasdsad";
    
    preg_match_all($re, $str, $matches);
    

    【讨论】:

    • [\s\S] 本质上是.
    • @hjpotter92 你也可以使用[^\]]+ 而不是[\s\S]+
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2017-06-06
    相关资源
    最近更新 更多