Php 使用preg_Match_all匹配模式并排除子字符串
我需要找到放在开始和结束之间的所有字符串,从匹配的字符串中排除填充子字符串。我找到的最好方法是Php 使用preg_Match_all匹配模式并排除子字符串,php,regex,preg-match-all,regex-lookarounds,Php,Regex,Preg Match All,Regex Lookarounds,我需要找到放在开始和结束之间的所有字符串,从匹配的字符串中排除填充子字符串。我找到的最好方法是 $r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ; preg_match_all('/START(.*?)END/',str_replace('PADDING','',$r),$m); print(join($m[1])); > thisiswhatIwantto
$r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ;
preg_match_all('/START(.*?)END/',str_replace('PADDING','',$r),$m);
print(join($m[1]));
> thisiswhatIwanttofind
我想用尽可能小的代码大小来实现这一点:有一个只包含preg_match_all而不包含str_replace的较短代码,它最终直接返回字符串而不包含连接数组?我试过一些环顾四周的表情,但找不到合适的
$r="stuffSTARTthisPADDINGisENDstuffstuffSTARTwhatPADDINGIwantPADDINGtoPADDINGfindENDstuff" ;
preg_match_all('/(?:START)(.*?)(?:END)/',str_replace('PADDING','',$r),$m);
var_dump(implode(' ',$m[1]));
可以,但我想你想要更快的。你也可以像这样使用preg\u replace\u回调:
$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
这将返回您使用单个正则表达式模式要查找的内容
说明:-
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
PADDING
是介于START
和END
之间的文本吗?否则,PADDING
将是什么类型的字符?PADDING是一个固定的ascii字符串
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