-5

I am trying to add a string after the first occurrence of an <img> tag.

Let say that I have the following html markup:

<p>text here text here text here text here text here
<img class="img-class" src="image1.jpg" srcset="" alt="" />
text here text here text here text here text here text here text here
text here text here <img class="img-class" src="image2.jpg" srcset="" alt="" />
text here text here text here text here

Using a Regular Expression - How can add text after the first <img> tag?

Broshi
  • 3,334
  • 5
  • 37
  • 52

2 Answers2

0

Try this:

preg_replace('#(<img[^>]* />)#','$1.$myText',$content,1)

Where $text is the string you want to add the extra and YOURTEXT should be a variable to add after the first image. Remember to add a space to YOURTEXT.

Ukuser32
  • 2,147
  • 2
  • 22
  • 32
0

Got it! this is how I did it:

$myText = 'Text I want to add';
preg_match('#(<img[^>]* />)#',$content,$matches);
if ( ! empty( $matches ) AND ! empty( $matches[0] ) )
{
    $content = str_replace($matches[0], $matches[0] . $myText, $content);
}

This will add $myText right after the first <img> match inside $content

Broshi
  • 3,334
  • 5
  • 37
  • 52