问题
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