1

I have html string in variable in php. I want to get tag from it. For example :

  $str ='<p><img src="link"></p><p>text</p>';

how can I get <img src="link"> (or any img tag plus its content) from this string?

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40

4 Answers4

3

All answers seem a bit messy and include regex.

You dont need it.

$str ='<p><img src="link"></p><p>text</p>';
echo strip_tags($str, '<img>');

Will work nicely.

Strip_tags Ref

Community
  • 1
  • 1
Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • did you try your code? Why it displays string `text` along with `img` tag? Because strip_tags removes only the tags not it's contents. – Avinash Raj Oct 24 '14 at 15:58
2

You can either use regular expressions, but you have to be careful to cater for any attributes that could be inside, or you can use the DOMDocument::loadHTML functionality along with DOMDocument::getElementsByTagName

$doc = new DOMDocument();

$doc->loadHTML($str);

// gets all img tags in the string    
$imgs = $doc->getElementsByTagName('img');

foreach ($imgs as $img) {    
    $img_strings[] = $doc->saveHTML($img);    
}

You then have all your img tags in the $img_strings variable.

In the foreach loop you can also get attributes within the tag: $img->getAttribute('src');

Titi
  • 1,126
  • 1
  • 10
  • 18
0

If I understand what you want to do correctly:

I would suggest something like what is described here.

They created a function to select the string contained between two particular strings. Here is their function:

function getInnerSubstring($string,$delim){
    // "foo a foo" becomes: array(""," a ","")
    $string = explode($delim, $string, 3); // also, we only need 2 items at most
    // we check whether the 2nd is set and return it, otherwise we return an empty string
    return isset($string[1]) ? $string[1] : '';
}

So long as there is not another set of "" in your HTML then this should work for you.

If you use this you could search for what is only between those two "

Community
  • 1
  • 1
Darksaint2014
  • 172
  • 1
  • 11
  • If you are going to vote something down please leave an explanation or else nothing can be fixed to be more helpful – Darksaint2014 Oct 24 '14 at 15:18
  • If you're going to post a link as an answer, try actually adding the relevant bit of information from that link in your answer. [Here's why it matters](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers) – Novocaine Oct 24 '14 at 15:19
  • I didnt downvote this @Darksaint2014 but i would suggest offering some example to to OP – Pogrindis Oct 24 '14 at 15:19
  • Thank you for giving feedback – Darksaint2014 Oct 24 '14 at 15:21
-1

User Regex in php. You should write regular expression for it

http://php.net/manual/en/function.preg-match.php

<img\s[^<>]*>
Misha Akopov
  • 12,241
  • 27
  • 68
  • 82