php正则表达式最后一场比赛

时间:2013-07-22 19:36:09

标签: php regex

条件: 我有来自wysiwig(简短)的html代码。 我需要将readmore链接注入最后一个paragrpaph(p-tag)

public function injectReadMore($html){
        if( $this->is_html($html) ){
            return preg_replace('#\<\/p\>$#isU',' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a>$0', $html);
        } else {
            return '<p>'.$html.' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a></p>';
        }
    }

是的。我写的不对。如果

$html = '<p>sdfgsdfg</p><div><p>sdfgsdfg</p> </div> ';

失败。

试过regexp:

'#\<\/p\>[^p]+?$#isU'
'#\<\/p\>[^\/p]+?$#isU'
'#\<\/p\>[^[\/p]]+?$#isU'

和RegExp的相同变体。我不明白,也许全部;)

帮忙。谢谢,兄弟。

3 个答案:

答案 0 :(得分:2)

你可以使用带有负前瞻的正则表达式模式(?!...)

</p>(?!.*</p>)

regexp

示例:http://www.debuggex.com/r/rgV-ddCbL-BH_rL_/0

答案 1 :(得分:2)

使用常规字符串替换而不是regexp很容易做到:

$pos = strripos($html, '</p>'); // Find last paragraph end
if ($pos !== false) { // Use exact matching, to distinguish 0 from false
    // Insert anchor before it
    $html = substr_replace($html, ' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a>', $pos, 0);
}
return $html;

答案 2 :(得分:1)

否定前瞻但请记住逃避你的HTML。

preg_replace('/\<\/p\>(?!.*\<\/p\>)/isU', '<a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a></p>', $html);