[英]php regexp last match
Condition: I have a peace of html code from wysiwig (Brief). 条件:我有一个来自wysiwig(Brief)的html代码。 I need to inject readmore link to the last paragrpaph (p-tag)
我需要注入readmore链接到最后一个参数(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>';
}
}
Yep. 是的。 What i wrote it's not right.
我写的东西不对。 Cuz if
因为如果
$html = '<p>sdfgsdfg</p><div><p>sdfgsdfg</p> </div> ';
Fail. 失败。
Tried regexp's: 尝试过正则表达式的:
'#\<\/p\>[^p]+?$#isU'
'#\<\/p\>[^\/p]+?$#isU'
'#\<\/p\>[^[\/p]]+?$#isU'
and the same variants of RegExp. 和RegExp的相同变体。 I don't understand something, maybe all;)
我什么都不懂,也许全部;)
Help pls. 帮助请。 Thanks, Brothers.
谢谢兄弟们。
You can use regex pattern with negative lookahead (?!…) 您可以将正则表达式模式使用负前瞻(?!…)
</p>(?!.*</p>)
Example: http://www.debuggex.com/r/rgV-ddCbL-BH_rL_/0 例如: http : //www.debuggex.com/r/rgV-ddCbL-BH_rL_/0
This is easy to do with regular string replacement instead of regexp: 使用常规字符串替换而不是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;
负前瞻,但请记住转义html。
preg_replace('/\<\/p\>(?!.*\<\/p\>)/isU', '<a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a></p>', $html);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.