PHP replacing all occurances of certain string pattern in HTML formatted text

梦想与她 提交于 2020-01-14 03:32:34

问题


I have input text that can be long HTML text with tags and so on. Example of input can be something like:

<p>Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipiscing elit.<p>
<p>%image1%</p>
<h2>Lorem ipsum</h2>
<p>Cum sociis natoque penatibus et magnis dis parturient montes.</p>
<p>%image2%</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
<p>%image3%</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
...

What would be the easiest way of finding all occurrences of text between %% characters and replacing that with <img src="image1.jpg">?


回答1:


preg_replace('|%(.+)%|', '<img src="$1">', $text );

working example: http://codepad.org/20Oz3Vok




回答2:


try using preg_replace ('/%(.+?)%/', '<img src="image1.jpg">', $string); i might be a little bit off on the regex pattern as to rather u need to escape %, and if ? is the greedy symbol.




回答3:


Try this:

preg_replace('|%(\w+)%|', '<img src="$1">', $string);

It will only allow alphanumeric characters, as well as underscores (to prevent the problem @AlexanderVarwijk pointed out in the comments).



来源:https://stackoverflow.com/questions/9432947/php-replacing-all-occurances-of-certain-string-pattern-in-html-formatted-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!