如何修改preg_replace_callback模式以匹配带有或不带属性的<p>元素?</p>

时间:2012-01-24 15:13:49

标签: php regex

如何更改模式以使其匹配带有属性的p标签?目前,它仅匹配没有属性的p标签。

$replaced_content = preg_replace_callback('#(<p>.*?</p>)#', 'p_callback', $content);

示例内容#1:

<div style="margin: 10px 0;">
    <a href="test.jpg" target="_blank" rel="nofollow">
        <img style="float: left; margin: 10px; max-width: 25%;" title="test" src="test.jpg" alt="test" />
    </a>
    <p>
        <a href="test" target="_blank" rel="nofollow">
            <img title="PDF file" src="test.png" alt="PDF file" /> 
            <span style="font-weight: bold; text-transform: capitalize;">Test ...</span>
        </a>
        <span>test <strong>test</strong> test? test, test, i.e., </span>
        <a href="test.pdf" target="_blank" rel="nofollow"> ... Get Content Here</a>
    </p>
</div>

示例内容#2

<div style="margin: 10px 0;">
    <a href="test.jpg" target="_blank" rel="nofollow">
        <img style="float: left; margin: 10px; max-width: 25%;" title="test" src="test.jpg" alt="test" />
    </a>
    <p style="margin:10px; float:left">
        <a href="test" target="_blank" rel="nofollow">
            <img title="PDF file" src="test.png" alt="PDF file" /> 
            <span style="font-weight: bold; text-transform: capitalize;">Test ...</span>
        </a>
        <span>test <strong>test</strong> test? test, test, i.e., </span>
        <a href="test.pdf" target="_blank" rel="nofollow"> ... Get Content Here</a>
    </p>
</div>

1 个答案:

答案 0 :(得分:3)

使用s (PCRE_DOTALL)修饰符:

根据Dor Shemer的评论编辑

$replaced_content = preg_replace_callback('#(<p[\s>].*?</p>)#s', 'p_callback', $content