Home  >  Article  >  Backend Development  >  Regular Expression - How to use regular expression to get the content of a tag in php?

Regular Expression - How to use regular expression to get the content of a tag in php?

WBOY
WBOYOriginal
2016-12-05 13:44:111792browse

<code><!-- 1 -->
<a class="myclass" target="_blank" href="http://www.taobao.com/">我是内容1</a>
<!-- 2 -->
<a target="_blank" class="myclass" href="http://www.baidu.com/">我是内容2</a>
<!-- 3 -->
<a class="noclass" target="_blank" href="http://www.foobar.com/">不包含我</a>
</code>

Like the tag above, I want to get the content of 1 and 2 of the a tag (I am content 1, I am content 2), but I don’t want 3 (not including me). The only difference between them is that the classtags are different classlocation may also be different! ! ! **

How to use regular expression to obtain it?

Reply content:

<code><!-- 1 -->
<a class="myclass" target="_blank" href="http://www.taobao.com/">我是内容1</a>
<!-- 2 -->
<a target="_blank" class="myclass" href="http://www.baidu.com/">我是内容2</a>
<!-- 3 -->
<a class="noclass" target="_blank" href="http://www.foobar.com/">不包含我</a>
</code>

Like the tag above, I want to get the content of 1 and 2 of the a tag (I am content 1, I am content 2), but I don’t want 3 (not including me). The only difference between them is that the classtags are different classlocation may also be different! ! ! **

How to use regular expression to obtain it?

Thanks for the invitation.

<code class="php">$str = '<a class="myclass" target="_blank" href="http://www.taobao.com/">我是内容1</a>
<a target="_blank" class="myclass" href="http://www.baidu.com/">我是内容2</a>
<a class="noclass" target="_blank" href="http://www.miyahuo.com/">不包含我</a>';

preg_match_all('#<a .*class="myclass".*>(.*)</a>#', $str,$m);
print_r($m);
/*
Array
(
    [0] => Array
        (
            [0] => <a class="myclass" target="_blank" href="http://www.taobao.com/">我是内容1 <a target="_blank" class="myclass" href="http://www.baidu.com/">我是内容2 Array
        (
            [0] => 我是内容1
            [1] => 我是内容2
        )

)
*/</code>

Thanks for the invitation, correct answer upstairs

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn