条件: 我有来自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的相同变体。我不明白,也许全部;)
帮忙。谢谢,兄弟。
答案 0 :(得分:2)
答案 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);