1

I want to capture all what is between <td id="adress">and </td>:

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

That means: multi line capture AND stops at first occurence of so result should be:

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

Any clue ?

I tried with:

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

But this does not stop at first </td>.

2 Answers 2

1

If you want the regex engine to stop after the first occurrence then you need to use preg_match function instead of 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]);

Output:

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

If you add a question mark after the .*, the match will stop at the first occurrence of what follows, e.g. </td>. You don't have to use preg_match_all either:

$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);

Output:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.