Home  >  Article  >  Backend Development  >  一个php的正则表达式匹配,结果感觉不太对?

一个php的正则表达式匹配,结果感觉不太对?

WBOY
WBOYOriginal
2016-06-06 20:35:211151browse

<code><br>$content = '

<p>
    这里是帖子的内容。
</p>




<p>
    <img src="/upload/image/20150429/1430288803746265.gif" title="1430288803746265.gif" alt="gif-0009.gif">
</p>




<p>
    <span>这里是帖子的其他内容</span>
</p>




<pre class="brush:cf;toolbar:false">$user = $this->session->get(&#39;auth&#39;);
                $baa_id=(int)$_POST[&#39;baa_id&#39;];
                $time = date(&#39;Y-m-d H:i:s&#39;);
                

这里是帖子的其他内容

'; preg_match_all('#

]*>([^(?:?p>)]*)

#',$content,$matches); print_r($matches);

匹配的结果:

<code>Array</code><code>(
    [0] => Array
        (
            [0] => 

<p>
    这里是帖子的内容。
</p>


        )

    [1] => Array
        (
            [0] => 
    这里是帖子的内容。

        )

)
</code>

为什么p标签之间有img span等其他标签的内容不能被匹配呢?

回复内容:

<code><br>$content = '

<p>
    这里是帖子的内容。
</p>




<p>
    <img src="/upload/image/20150429/1430288803746265.gif" title="1430288803746265.gif" alt="gif-0009.gif">
</p>




<p>
    <span>这里是帖子的其他内容</span>
</p>




<pre class="brush:cf;toolbar:false">$user = $this->session->get(&#39;auth&#39;);
                $baa_id=(int)$_POST[&#39;baa_id&#39;];
                $time = date(&#39;Y-m-d H:i:s&#39;);
                

这里是帖子的其他内容

'; preg_match_all('#

]*>([^(?:?p>)]*)

#',$content,$matches); print_r($matches);

匹配的结果:

<code>Array</code><code>(
    [0] => Array
        (
            [0] => 

<p>
    这里是帖子的内容。
</p>


        )

    [1] => Array
        (
            [0] => 
    这里是帖子的内容。

        )

)
</code>

为什么p标签之间有img span等其他标签的内容不能被匹配呢?

已更新,preg_match_all('#<p>]*)>([\s\S]*?)</p>#',$content,$matches);
这是完整的写法,你的问题在于你错误的以为[^(?:?p>)]代表的是除<p>>或者<code>

标签以外的匹配。实际上[^(?:?p>)]等同于[^?:?p>]这样看就明白了吧

不用正则,xpath搞定

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