>  기사  >  백엔드 개발  >  一个php的正则表达式匹配,结果感觉不太对?

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

WBOY
WBOY원래의
2016-06-06 20:35:211149검색

<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搞定

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.