Search code examples
phpregexpreg-match

php regular expression preg_match with html tag


I write some simple code

$test='<span class="h2">AAAA</span> <div>aaaa</div> <p>ccc</p>';
preg_match('<\<(.*)>',$test,$matches);
echo $matches[0]

The result is :

AAAA

aaaa

ccc

I could not understand why $matches[0] will be like that.

Could someone explain a little bit?

Thanks.


Solution

  • That is the output you see in the browser. Check the HTML source or run from command line. What you really get is:

    <span class="h2">AAAA</span> <div>aaaa</div> <p>ccc</p>
    

    Why? Because <> is the delimiter of your preg! So the actual regular expression is just \<(.*), saying "give me a less than sign and then any number of anything." preg is greedy so it will consume as much as it can so that's why.