PHP在字符串前后插入一些文本
我对PHP还是很陌生,有一个包含HTML页面的String.我需要在任何 HR HTML标签之前和之后插入一些自定义代码.示例:
I'm pretty new to PHP and have a String which contains an HTML page. I'd need to insert some custom code BEFORE and AFTER any HR HTML tag. Example:
<html>
....
<p>INSERT HERE</p>
<hr class="pagebreak">
<p>INSERT HERE</p>
<p>INSERT HERE</p>
<hr class="pagebreak">
<p>INSERT HERE</p>
....
</html>
我尝试使用 preg_replace 和 substr_replace 的几种组合,但是我仍然无法在所有需要的地方插入自定义代码. 有人可以帮助我解决这个难题吗? P.s.我需要使用PHP标准的String函数-我无法使用任何HTML解析库,因为我无法控制服务器上可用的PHP库. 非常感谢 琳达
I've tried with several combinations of preg_replace and substr_replace, however I still couldn't manage to insert the custom code in all places I need. Anybody can help me to solve this puzzle ? P.s. I need to use PHP standard String functions- I cannot use any HTML parsing library since I don't have control over the PHP libraries available on the server. Thanks a lot Linda
您所需要获得的只是一个好的正则表达式,假设您设法使其至少部分起作用,那么您的表达式可能很差(示例会有所帮助).我为您测试了此代码,它应该可以在您的所有<hr>
上运行:
All you need to get is good regular expression, assuming that you managed to get it work at least partially, you propably had bad expression (example would help). I tested this code for you and it should work on all your <hr>
s:
$newtext=preg_replace("#(<hr[^>]*>)#s",$yourprefix."\${1}".$yoursuffix,$oldtext);
可变的旧文本是您以前拥有的,新文本是您想要的,而前缀和后缀是您想要在hr标签周围添加的
variable oldtext is what you had before, new text is what you want, and prefix and suffix is what you want to add around hr tag