【问题标题】:Match pattern and exclude substrings with preg_match_all使用 preg_match_all 匹配模式并排除子字符串
【发布时间】:2013-03-22 11:51:10
【问题描述】:

我需要找到所有放在 START 和 END 之间的字符串,从匹配的字符串中排除 PADDING 子字符串。我发现的最好方法是

$r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ;
preg_match_all('/START(.*?)END/',str_replace('PADDING','',$r),$m);
print(join($m[1]));
> thisiswhatIwanttofind

我想用尽可能小的代码大小来做到这一点:只有 preg_match_all 而没有 str_replace 的更短,最终直接返回没有连接数组的字符串?我尝试了一些环视表达式,但找不到合适的表达式。

【问题讨论】:

  • PADDING 是介于STARTEND 之间的文字吗?不然PADDING会是什么人物?
  • PADDING 是一个固定的 ascii 字符串

标签: php regex preg-match-all regex-lookarounds


【解决方案1】:
$r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff";
echo preg_replace('/(END.*?START|PADDING|^[^S]*START|END.*$)/', '', $r);

这应该使用单个正则表达式模式返回thisiswhatIwanttofind

解释:-

END.*?START  # Replace occurrences of END to START
PADDING      # Replace PADDING
^[^S]*START  # Replace any character until the first START (inclusive)
END.*$       # Replace the last END and until end of the string

【讨论】:

    【解决方案2】:
    $r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ;
    preg_match_all('/(?:START)(.*?)(?:END)/',str_replace('PADDING','',$r),$m);
    var_dump(implode(' ',$m[1]));
    

    可以,但我猜你想要更快的东西。

    【讨论】:

      【解决方案3】:

      你也可以像这样使用 preg_replace_callback:

      $str = preg_replace_callback('#.*?START(.*?)END((?!.*?START.*?END).*$)?#', 
                 function ($m) {
                     print_r($m);
                     return str_replace('PADDING', '', $m[1]);
                 }, $r);
      
      echo $str . "\n"; // prints thisiswhatIwanttofind
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2022-01-03
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 2012-09-26
        相关资源
        最近更新 更多