1

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

4
  • Word of warning: The current trend is 10% in comparison to 5% last year. %graph1% (Either don't allow a space after % or prepare for some trouble with <img src=" in comparison to 5.jpg"> Commented Feb 24, 2012 at 15:10
  • I don't quite understand this comment? Can you please explain? Commented Feb 24, 2012 at 15:41
  • BTW: I can force something else then %image1% to users who will use this? Should I use #iamge1# or something else instead? Commented Feb 24, 2012 at 15:43
  • What I mean, is that if you have a string that contains two of your selection characters, '%' in this case you will select the text in between those characters and might unintentionally add an image where you don't want one. Commented Feb 24, 2012 at 15:49

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

-1. Would explode on %image1% text %image2%. It will create only one image.
0
preg_replace('|%(.+)%|', '<img src="$1">', $text );

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

1 Comment

Is there a way to replace every occurrence separately? Because I need to see what's the value between %% and then accordingly to this find the right image in DB and put it in...!
-1

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

1 Comment

of course it will. \w matches alphanumeric characters, plus underscores. Thats [a-zA-Z0-9_],

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.