简体   繁体   中英

How to use preg match to get the contents of this html tag?

I am trying to get at the desired content in this tag:

<p class="address">
desired content
</p>

this is my attempt:

preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/", $contents, $matches);

But the $matches array is empty. Please help.

Thanks

You could try this:

$contents = '<p class="address">desired content</p>';
$res = preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/s", $contents, $matches);
var_dump($res);
var_dump($matches);

$matches is not empty, right?

  1. you need to set the PCRE_DOTALL flag to make . also match \\n - see modifiers
  2. use .*? (ungreedy operator) to not prevent matching </p> in the capture group
  3. you can use a different pattern delimiter and single quotes to remove all the backslashes, makes your pattern much more readable!

like so:

<?php
$contents = '<p class="address">
desired content
</p>';
$res = preg_match_all('#<p class="address">(.*?)</p>#s', $contents, $matches);
var_dump($matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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