简体   繁体   中英

How I can get an img tag from string

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?

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

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');

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 "

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

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

<img\s[^<>]*>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM