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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:35:21
Original
1215 people have browsed it

<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:php;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;);
                
Copy after login

这里是帖子的其他内容

'; preg_match_all('#]*>([^(?:)]*)

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

匹配的结果:

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

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


        )

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

        )

)
</code>
Copy after login
Copy after login

为什么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:php;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;);
                
Copy after login

这里是帖子的其他内容

'; preg_match_all('#]*>([^(?:)]*)

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

匹配的结果:

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

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


        )

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

        )

)
</code>
Copy after login
Copy after login

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

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

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

不用正则,xpath搞定

Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template