Match pattern and exclude substrings with preg_match_all

I need to find all the lines located between START and END, except for the PADDING substring from the matched string. The best way I've found is

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

I want to do this with a minimal code size: is it shorter only with preg_match_all and without str_replace, which ultimately returns directly a string without connection arrays? I tried with some external expressions, but I can not find the correct one.

+4
source share
3 answers
 $r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff"; echo preg_replace('/(END.*?START|PADDING|^[^S]*START|END.*$)/', '', $r); 

This should return you thisiswhatIwanttofind using a single regex pattern

Explanation: -

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

will work, but I think you want something faster.

0
source

You can also 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 
0
source

All Articles