繁体   English   中英

PHP多行preg_match_all

[英]php multiline preg_match_all

我有以下代码:

$content = <<<HTML
<p>{wrapper btnlabel=&quot;AAA&quot;}zzzzzzzzzzzzzzzzzzzz{/wrapper}</p>

<p>{wrapper btnlabel=&quot;Text&quot;}</p>

<table>
<tbody>
<tr>
<th scope="row">123</th>
<td>1 123</td>
<td>12 123</td>
<td>3 123</td>
<td>1 123 123</td>
</tr>
<tr>
<th scope="row">123</th>
<td>2700 123.</td>
<td>1800 123.</td>
<td>1000 123.</td>
<td>300 123.</td>
</tr>
</tbody>
</table>

<p>{/wrapper}</p>
HTML;

preg_match_all('#(?>{wrapper btnlabel=(?>"|&quot;)(.+)(?>"|&quot;)})(.*){/wrapper}#', $content, $matches);
var_dump($matches);

模式与第二个{wrapper...不匹配。 我认为是因为它分为多行。 但是,当我尝试使用s修饰符时,它会匹配从第一个{wrapper到最后一个{/wrapper}中的整个内容。 \\n替换为''无济于事。 所以我很困惑。 也许我想念什么? https://ideone.com/ZMpSJ7-这是相同的测试代码

就像我在评论中提到的那样,您应该非常注意贪婪的模式,仅在需要获取尽可能大的子字符串(包括子块)时才使用它们。 在其他情况下,当您需要单个子字符串时,请使用惰性匹配。

这是一个固定的正则表达式

(?>{wrapper btnlabel=(?>"|&quot;)(.+?)(?>"|&quot;)})(.*?){\/wrapper}

样例代码:

$re = "/(?>{wrapper btnlabel=(?>\"|&quot;)(.+?)(?>\"|&quot;)})(.*?){\\/wrapper}/s"; 
$str = "<p>{wrapper btnlabel=&quot;AAA&quot;}zzzzzzzzzzzzzzzzzzzz{/wrapper}</p>\n\n<p>{wrapper btnlabel=&quot;Text&quot;}</p>\n\n<table>\n<tbody>\n<tr>\n<th scope=\"row\">123</th>\n<td>1 123</td>\n<td>12 123</td>\n<td>3 123</td>\n<td>1 123 123</td>\n</tr>\n<tr>\n<th scope=\"row\">123</th>\n<td>2700 123.</td>\n<td>1800 123.</td>\n<td>1000 123.</td>\n<td>300 123.</td>\n</tr>\n</tbody>\n</table>\n\n<p>{/wrapper}</p>"; 
preg_match_all($re, $str, $matches);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM