Page 1 of 1
Locating all IMG tags and using their URLs
Posted: Tue Apr 06, 2010 8:12 pm
by rocklee
Hi, I'm currently using str_replace to parse through my content to replace IMG tags with HTML codes <IMG src....>. An example code is as followed :
Code: Select all
$content = str_replace("[img]", "<img WIDTH=480 class='image_center' src='", $content);
$content = str_replace("[/img]", "'>", $content);
$content is a bunch of text that contains tags, it may have a number of IMG tags, which is why I use str_replace to quickly browse through it and replace them for HTML output.
This works fine but I want to get the URL address of my images and use them as a link as well. I can't do it with this set up because it only replaces the tags, i want to get the url between the tags.
Any ideas?
Re: Locating all IMG tags and using their URLs
Posted: Wed Apr 07, 2010 12:20 am
by thinsoldier
Regular Expressions / regex / regexp / preg_match() / etc...
regexpal.com...
...or... is this like a BBCode format with the [img] tag?
What exactly are you planning on doing with the img urls? If you just want to gather a list of them 1 time you could just do your current string replace then dump the resulting html into a simplexml or dom object and use xpath or javascript-style DOM manipulation to quickly getElementsByTagName then loop through them and grab their src attributes.
Re: Locating all IMG tags and using their URLs
Posted: Wed Apr 07, 2010 12:54 am
by rocklee
Hi yes its like a bbcode, my content can have many image tags.
I'm hoping for a process that will grab the URLS between all my IMG tags and replace the tags with DIV, IMG and A HREF references.
I was told not to use regex.
Re: Locating all IMG tags and using their URLs
Posted: Wed Apr 07, 2010 10:28 am
by thinsoldier
If it's really really close to BBCODE there are definitely functions/classes/libraries for parsing bbcode (I'll bet they use regular expressions) that may allow you to decide exactly how the [img] replacement is formatted.
Is this a one time conversion process or will you be storing your content always with bbcode and transforming it on every page view?
Some people will probably say that regular expressions are slow for some reason but I use Markdown instead of BBCode on all my sites and the Markdown_Parser has a tonne of regular expressions in it. I don't see a speed issue.
Re: Locating all IMG tags and using their URLs
Posted: Thu Apr 08, 2010 8:10 pm
by rocklee
Thanks!
That gave me an idea in borrowing the idea from another tag URL to add additional information to the code :
Code: Select all
$content = str_replace('/\[img\=(.*?)\](.*?)\[\/img\]/is, "<a href='$1'><img src='$2'></a> ", $content);
Even though $1 and $2 is the same, I could add other information like filesize.
