Jump to content

Split String At <Img> Tag And Place In New Varaible


matthewtbaker

Recommended Posts

Hi,

 

I have a string which I am pulling from a MySQL DB which unfortunately looks like the following.

 

<p><img src="myimage.jpg" border="0" /></p>
<p>My short paragraph</p>

 

 

I would like to pull out <img src="myimage.jpg" border="0" /> and place it in a separate variable 'strImage' (so I can echo it elsewhere), and then place the remainder of the string in a second variable 'strText'.

 

Note: The <img src> and <border> values will vary depending on the article I pull from the database.

 

What method should I use to make this happen?

 

Thank you so much for your help in advance!

Matt

PHP´s strip_tags function should do the trick

http://php.net/strip-tags

 

$html = '<p><img src="myimage.jpg" border="0" /></p>
<p>My short paragraph</p>';
$strImage = strip_tags($html, "<img>");

 

I suppose you could do the same for your second varialbe, but you will have to come up with something to get rid of blank P tags.

Hi Zane,

 

Thanks for solution. Unfortunately it does not do exactly what I need. It does remove the image perfectly when allowing the tag <p>, but when using your example of allowing <img> it does not. Probably because the the <p> tags are closed so the text is still returned?

 

$html = '<p><img src="myimage.jpg" border="0" /></p>
<p>My short paragraph</p>';
$strImage = strip_tags($html, "<p>");

 

Returns

 

<p></p><p>My short paragraph</p>

 

Which is great, but

 

$html = '<p><img src="myimage.jpg" border="0" /></p>
<p>My short paragraph</p>';
$strImage = strip_tags($html, "<img>");

 

returns

 

<img src="myimage.jpg" border="0" />My short paragraph

 

So how can I put the <img> info into another variable?

 

Thanks again.

There is always the DOMDocument route.

$doc=new DOMDocument;
$doc->loadHTML('<p><img src="myimage.jpg" border="0" /></p>
<p>My short paragraph</p>');
$path=new DOMXPath($doc);
foreach ($path->query('//img') as $found)
   echo $doc->saveXML($found);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.