0

how I get the img code from a text? Now I get the code and URL if the tag looks like: text text <img src = "image.gif" />, but if the code is <img src = "image.gif" target = _blank />, then I get the URL: "image.gif" target = _blank.

So, how correctly find img full code and URL?

Thanks

preg_match_all('/\<img src = (.*?)\/>/', $input, $all_img);
Gumbo
  • 643,351
  • 109
  • 780
  • 844
user319854
  • 3,980
  • 14
  • 42
  • 45

1 Answers1

5

Don’t try to parse HTML with regular expressions; use an HTML parser like PHP’s DOM library or the PHP Simple HTML DOM Parser instead (see Gordon’s comment for further alternatives).

Here’s an example with the PHP Simple HTML DOM Parser:

$html = str_get_html('…');
foreach ($html->find('img[src]') as $img) {
    echo $img->getAttribute('src');
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 2
    Suggested third party alternatives to [SimpleHtmlDom](http://simplehtmldom.sourceforge.net/) that actually use [DOM](http://php.net/manual/en/book.dom.php) instead of String Parsing: [phpQuery](http://code.google.com/p/phpquery/), [Zend_Dom](http://framework.zend.com/manual/en/zend.dom.html), [QueryPath](http://querypath.org/) and [FluentDom](http://www.fluentdom.org). – Gordon Oct 01 '10 at 12:03
  • @user319854: Use the `__toString` method: `$img->__toString()`. – Gumbo Oct 01 '10 at 12:39