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

Link to comment
Share on other sites

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.

Edited by Zane
Link to comment
Share on other sites

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.

Edited by matthewtbaker
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.