简体   繁体   中英

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

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"> ?

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.

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

工作示例: http : //codepad.org/20Oz3Vok

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM