2013-04-01 42 views
4

我需要找到所有放在START和END之間的字符串,包括來自匹配字符串的PADDING子字符串。我發現最好的辦法是匹配模式和排除子字符串preg_match_all

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

我想用最小的代碼大小可能做到這一點:有一個更短的只有preg_match_all沒有str_replace函數,最終直接返回,而不加入陣列的字符串?我已經嘗試了一些lookaround表達式,但我找不到合適的表達式。

+0

是'PADDING 'START'和'END'之間的字面文本?否則,「PADDING」是什麼類型的字符? –

+0

PADDING是一個固定的ascii字符串 – Emilio

回答

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 
0
$r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ; 
preg_match_all('/(?:START)(.*?)(?:END)/',str_replace('PADDING','',$r),$m); 
var_dump(implode(' ',$m[1])); 

會工作,但我想你想要更快的東西。

0

您還可以使用使用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