I would like to create a page where all images which reside on my website are listed with title and alternative representation.
I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract src
, title
and alt
from this HTML:
<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />
I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).
the below code worked for me in wordpress...
it extracts all the image sources from the code
cheers!
EDIT : now that I know better
Using regexp to solve this kind of problem is a bad idea and will likely lead in unmaintainable and unreliable code. Better use an HTML parser.
Solution With regexp
In that case it's better to split the process into two parts :
I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :
Then we get all the img tag attributes with a loop :
Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using ob_start and loading / saving from a text file.
How does this stuff work ?
First, we use preg_ match_ all, a function that gets every string matching the pattern and ouput it in it's third parameter.
The regexps :
We apply it on all html web pages. It can be read as every string that starts with "
<img
", contains non ">" char and ends with a >.We apply it successively on each img tag. It can be read as every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ().
Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this online regexp tester.
EDIT : answer to the first comment.
It's true that I did not think about the (hopefully few) people using single quotes.
Well, if you use only ', just replace all the " by '.
If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].
The script must be edited like this
foreach( $result[0] as $img_tag)
because preg_match_all return array of arrays
Use xpath.
For php you can use simplexml or domxml
see also this question
this will extract anchor tag nested with image tag
You can also try SimpleXML if the HTML is guaranteed to be XHTML - it will parse the markup for you and you will be able to access the attributes just by their name. (There are DOM libraries as well if it's just HTML and you can't depend on the XML syntax.)