4

一致する文字列から PADDING 部分文字列を除外して、START と END の間に配置されたすべての文字列を検索する必要があります。私が見つけた最良の方法は

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

可能な限り最小のコードサイズでこれを行いたい: preg_match_all のみで str_replace を使用せず、最終的に結合配列なしで文字列を直接返す短いものがありますか? ルックアラウンド式をいくつか試してみましたが、適切な式が見つかりません。

4

3 に答える 3

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
于 2013-04-02T06:57:46.710 に答える
0

次のように use 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
于 2013-04-01T21:47:29.573 に答える