tags:

views:

2770

answers:

10

Hello,

I would like to know how this can be achieved.

Assume: That there's a lot of html code containing tables, divs, images, etc.

Problem: How can I get matches of all occurances. More over, to be specific, how can I get the img tag source (src = ?).

example:

<img src="http://example.com/g.jpg" alt="" />

How can I print out http://example.com/g.jpg in this case. I want to assume that there are also other tags in the html code as i mentioned, and possibly more than one image. Would it be possible to have an array of all images sources in html code?

I know this can be achieved way or another with regular expressions, but I can't get the hang of it.

Any help is greatly appreciated.

+1  A: 

This works for me:

preg_match('@<img.+src="(.*)".*>@Uims', $html, $matches);
$src = $matches[1];
ceejayoz
I think your three dots need to be replaced with [^>], or you might end up matching everything between the first and last img tag on the page
Kip
I believe this will miss <img src='x.bmp' /> b/c of the single quotes
RC
actually the middle dot should be [^>"] i think
Kip
+16  A: 

While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.

What I recommend you do is use a DOM parser such as SimpleHTML and use it as such:

function get_first_image($html){
    require_once('SimpleHTML.class.php')

    $post_dom = str_get_dom($html);

    $first_img = $post_dom->find('img', 0);

    if($first_img !== null) {
     return $first_img->src';
    }

    return null;
}

Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.

A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression.

Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression:

<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>

And then again, the above can fail if:

  • The attribute or tag name is in capital and the i modifier is not used.
  • Quotes are not used around the src attribute.
  • Another attribute then src uses the > character somewhere in their value.
  • Some other reason I have not foreseen.

So again, simply don't use regular expressions to parse a dom document.


EDIT: If you want all the images:

function get_images($html){
    require_once('SimpleHTML.class.php')

    $post_dom = str_get_dom($html);

    $img_tags = $post_dom->find('img');

    $images = array();

    foreach($img_tags as $image) {
        $images[] = $image->src;
    }

    return $images;
}
Andrew Moore
I find this way very nice. This will work regardless of the attributes order correct? I mean src or SRC, will work? even if I put the alt and title tags..? This code will work on clients servers, so I need to make sure that whatever way they will put the src it will be extracted. Thanks so much for the fast and comlete answer.
Ahmad Fouad
**@Ahmad Fouad:** Correct, using a DOM Parser will work regarless of attribute order and capitalization.
Andrew Moore
why all the non-greedy "`\s*?`" in your regex? wouldn't plain-old greedy "`\s*`" be more efficient?
Kip
**@Kip:** Because you don't want it to be greedy.
Andrew Moore
Very nice. I think i will take this solution, because the users who posted regex, post various formulas and assume that the src will be entered in specific way and order.. this can become useless if the client put the src non-traditional way :( Thanks so much!
Ahmad Fouad
**@Ahmad Fouad:** In their defense, the major problem with the regex solutions below if the assumption that `src` will be between double-quotes.
Andrew Moore
@Andrew Moore I just discovered something that could be a problem for some clients with outdated servers.. Is this class only available for php5+, i mean it does not work with php4?
Ahmad Fouad
**@Ahmad Fouad:** Should be fairly easy to make it compatible with PHP4.
Andrew Moore
@Andrew Moore: I think I ripped you off with my answer, which is what I get for skimming. But notice that I used xpath. Do you think that the simplehtmlDOM add-on and the find method are a better way to go? I would probably endorse it more if it was adopted as a documented extension in PHP (or if it used standard syntax. I'm not a find of "find" even if it is more intuitive).
Anthony
**@Anthony:** `xpath` is great for XML DOM, but when it comes to HTML, I personally like CSS queries better. `SimpleHTMLDom->find()` does just that. It's all a matter of personal preference.
Andrew Moore
How do CSS queries work? I'm on the edge of my seat?
Anthony
**@Ahmad Fouad:** Here is a slighly older DOM Parser which will work on PHP4 - http://php-html.sourceforge.net/
Andrew Moore
**@Anthony:** They are not called *CSS Queries* per-se, but I don't have a better term for it. If you've used jQuery, you should be already famililar with them. `input[type=checkbox]` will return all `<input type="checkbox">`, `ul.some_class li a` will return all `<a>` which has, somewhere in the hierarchy, an `<li>` parent which has in turn a `<ul>` as a parent, but that `<ul>` needs to have `class="some_class"`... etc...
Andrew Moore
Now I remember, the proper term is **SELECTORS**. More examples here: http://docs.jquery.com/Selectors
Andrew Moore
Thanks Andrew for the tip! :)
Ahmad Fouad
@andrew: Xpath does the exact same thing, which is part of my resistance to the simplehtmlDOM add-on, because it doesn't use the Xpath syntax. This makes the syntax easier, but less functional and less portable. If you use an xpath query, you can port that query to any other language that does xpath, like js. For your examples: '//input[@type="checkbox"]', '//ul[class="some_class]//li//a"' I do agree that the CSS syntax is better (in jquery at least), but xpath can also do '//tr[td[@class="cost"] > 10]' to get all table rows which have a td of cost and the value is over 10.
Anthony
**@Anthony:** Until you start doing a selector like `input.some_class.another_class`... (Is it written as `<input class="some_class another_class">` or `<input class="another_class some_class">`. In the end, it's all a matter of personal preference.
Andrew Moore
@Andrew but you do want them to be greedy. if you have `<....img` (where "." is a space), then `<\s*?img` is going to try to match `<`, then `<.`, then `<..`, then `<...`, then finally it will succeed with `<....`. If you just used `<\s*img` it would be much faster
Kip
A: 

You can try this:

preg_match_all("/<img\s+src=\"(.+)\"/i", $html, $matches);
foreach ($matches as $key=>$value) {
    echo $key . ", " . $value . "<br>";
}
Knix
A: 

i assume all your src= have " around the url

<img[^>]+src=\"([^\"]+)\"

the other answers posted here make other assumsions about your code

Nir Levy
A: 

since you're not worrying about validating the HTML, you might try using strip_tags() on the text first to clear out most of the cruft.

Then you can search for an expression like

"/\<img .+ \/\>/i"

The backslashes escape special characters like <,>,/. .+ insists that there be 1 or more of any character inside the img tag You can capture part of the expression by putting parentheses around it. e.g. (.+) captures the middle part of the img tag.

When you decide what part of the middle you wish specifically to capture, you can modify the (.+) to something more specific.

dnagirl
A: 

I agree with Andrew Moore. Using the DOM is much, much better. The HTML DOM images collection will return to you a reference to all image objects.

Let's say in your header you have,

<script type="text/javascript">
    function getFirstImageSource()
    {
        var img = document.images[0].src;
        return img;
    }
</script>

and then in your body you have,

<script type="text/javascript">
  alert(getFirstImageSource());
</script>

This will return the 1st image source. You can also loop through them along the lines of, (in head section)

function getAllImageSources()
    {
        var returnString = "";
        for (var i = 0; i < document.images.length; i++)
        {
            returnString += document.images[i].src + "\n"
        }
        return returnString;
    }

(in body)

<script type="text/javascript">
  alert(getAllImageSources());
</script>

If you're using JavaScript to do this, remember that you can't run your function looping through the images collection in your header. In other words, you can't do something like this,

<script type="text/javascript">
    function getFirstImageSource()
    {
        var img = document.images[0].src;
        return img;
    }
    window.onload = getFirstImageSource;  //bad function

</script>

because this won't work. The images haven't loaded when the header is executed and thus you'll get a null result.

Hopefully this can help in some way. If possible, I'd make use of the DOM. You'll find that a good deal of your work is already done for you.

Anjisan
A: 

I don't know if you MUST use regex to get your results. If not, you could try out simpleXML and XPath, which would be much more reliable for your goal:

First, import the HTML into a DOM Document Object. If you get errors, turn errors off for this part and be sure to turn them back on afterward:

 $dom = new DOMDocument();
 $dom -> loadHTMLFile("filename.html");

Next, import the DOM into a simpleXML object, like so:

 $xml = simplexml_import_dom($dom);

Now you can use a few methods to get all of your image elements (and their attributes) into an array. XPath is the one I prefer, because I've had better luck with traversing the DOM with it:

 $images = $xml -> xpath('//img/@src');

This variable now can treated like an array of your image URLs:

 foreach($images as $image) {
    echo '<img src="$image" /><br />
    ';
  }

Presto, all of your images, none of the fat.

Here's the non-annotated version of the above:


 $dom = new DOMDocument();
 $dom -> loadHTMLFile("filename.html");

 $xml = simplexml_import_dom($dom);

 $images = $xml -> xpath('//img/@src');

 foreach($images as $image) {
    echo '<img src="$image" /><br />
    ';
  }
Anthony
A: 

Use this, is more effective:

preg_match_all('/<img [^>]*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
    echo $value."<br>";
}

Example:

$html = '
<ul>     
  <li><a target="_new" href="http://www.manfromuranus.com"&gt;Man from Uranus</a></li>       
  <li><a target="_new" href="http://www.thevichygovernment.com/"&gt;The Vichy Government</a></li>      
  <li><a target="_new" href="http://www.cambridgepoetry.org/"&gt;Cambridge Poetry</a></li>      
  <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value1.jpg" />
  <li><a href="http://www.verot.net/pretty/"&gt;Electronaut Records</a></li>      
  <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value2.jpg" />
  <li><a target="_new" href="http://www.catseye-crew.com"&gt;Catseye Productions</a></li>     
  <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value3.jpg" />
</ul>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="res/upload.jpg" />
  <li><a target="_new" href="http://www.manfromuranus.com"&gt;Man from Uranus</a></li>       
  <li><a target="_new" href="http://www.thevichygovernment.com/"&gt;The Vichy Government</a></li>      
  <li><a target="_new" href="http://www.cambridgepoetry.org/"&gt;Cambridge Poetry</a></li>      
  <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value4.jpg" />
  <li><a href="http://www.verot.net/pretty/"&gt;Electronaut Records</a></li>      
  <img src="value5.jpg" />
  <li><a target="_new" href="http://www.catseye-crew.com"&gt;Catseye Productions</a></li>     
  <img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value6.jpg" />
';   
preg_match_all('/<img .*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
    echo $value."<br>";
}

Output:

value1.jpg
value2.jpg
value3.jpg
res/upload.jpg
value4.jpg
value5.jpg
value6.jpg
inakiabt
regex assumes the html will fit into the regex pattern. Even if you have a simple yet perfect expression to find the data, you are still relying on a pattern-matching language that returns what it finds without any sort of integration with the original data/string. Your regex works like a charm, but using an extension that "speaks" html/xml helps me sleep at night, not to mention I can modify it to do other things without having to worry my modification will cause more problems then it fixes.
Anthony
This code gets the src of latest image inserted in the code. I tried to add 3 image tags in the code and it only gathers one image (one source).. can it be tweaked a bit to show all image sources in array?
Ahmad Fouad
Ahmad, did you try my answer? I think inakibt's answer only returns the first value because it has $matches[1], but it's been awhile since I've used preg_match_all to be sure how to modify it. Another reason why DOM and simplexml are a better solution.
Anthony
Also, Ahmad, my answer only requires having your PHP configured for simpleXML and DOM, which most PHP5 installs are by default. No need for downloading and including the simpleHTMLDOM add-on. With only 4 lines of code, you get the array you are looking for.
Anthony
I might consider regex because I have many clients who still use php 4. That is going to be a pain
Ahmad Fouad
**@Ahmad Fouad:** Here is a slighly older DOM Parser which will work on PHP4 - http://php-html.sourceforge.net/
Andrew Moore
@Andrew Moore thank you. I will use that.
Ahmad Fouad
It's not true that my code returns the first or the last match, it returns all "src" values. Post and example where my code is not working like I say.
inakiabt
Oh and I sleep at night too using GOOD regexs :)
inakiabt
**@inakiabt:** You didn't set the **`g`** (global) modifier, so it's stopping at the first match.
Andrew Moore
you are right, I change my regex, now it works.
inakiabt
A: 

thank you what i m search just find it thank you so much

A: 

Hi all, how I do filter, for example, .gif or .bmp images and extract only jpg, jpeg, png?

Lillo