php和regex:如何捕获多行并在第一次出现时停止


php and regex: how to capture multi-line and stops at first occurrence?

我想捕获<td id="adress"></td>:之间的所有内容

<td id="adress">
   hello<br>
   world<br>
   line3<br>
</td>
<td id="adress2">
   hello2<br>
   world2<br>
   line3<br>
</td>

这意味着:多行捕获AND在第一次出现时停止所以结果应该是:

   hello<br>
   world<br>
   line3<br>

有线索吗?

我尝试过:

preg_match_all("/<td id='"AddressHolder'">.*<'/td>/s", $source, $output_array);

但这并没有在第一个CCD_ 3处停止。

如果希望正则表达式引擎在第一次出现后停止,则需要使用preg_match函数而不是preg_match_all

$st = <<<EOT
<td id="adress">
   hello<br>
   world<br>
   line3<br>
</td>
<td id="adress2">
   hello2<br>
   world2<br>
   line3<br>
</td>
EOT;
preg_match('~<td id="adress[^"]*">[^'n]*'n'K.*?(?='n[^'n]*<'/td>)~s', $st, $match);
print_r($match[0]);

输出:

   hello<br>
   world<br>
   line3<br>

如果在.*后面添加问号,则匹配将在以下内容的第一次出现时停止,例如</td>。您也不必使用preg_match_all

$source = <<<EOS
<td id="adress">
   hello<br>
   world<br>
   line3<br>
</td>
<td id="adress2">
   hello2<br>
   world2<br>
   line3<br>
</td>
EOS;
preg_match("/<td id='"adress'">(.*?)<'/td>/s", $source, $matches);
$address = $matches[1];
print_r($address);

输出:

hello<br>
world<br>
line3<br>