Regex: IMG TAG

As i said before, i wanna share my Regex code, to catch the file name in HTML IMG TAG. Let me explain why i create this Regex code. I have IMG TAG that i need to catch only the file name. I don’t care about other attribute (ex. border=”0″) all i want just the file name inside the src attribute (ex. src=”file/path/i_want_this.jpg“);

First i have this code
[html]Test[/html]

And i want to capture the file_name.jpg, i use this
[code][^\'”>]*?)(?:\’|”|\\s) ([^>]*)>[/code]

After i get the file_name.jpg, i want to use it on hyperlink and also i want to change the path to absolute. The result should be like this
[html]Test[/html]

See, in HTML IMG TAG i just change the src attribute, i leave other attribute value like before. So i made some function in PHP using preg_replace to change that with Regex. Heres the code
[php]function get_image($content){
$content = preg_replace(‘/[^\'”>]*?)(?:\’|”|\\s) ([^>]*)>/’, ‘‘, $content);
return $content;
}[/php]

Thats it. You can modify the Regex to fulfill your need. FYI to get all the src value in HTML IMG TAG just change the Regex like this
[code][^\'”>]*?)(?:\’|”|\\s) ([^>]*)>[/code]

Happy Coding ;)

6 thoughts on “Regex: IMG TAG”

  1. Is it possible to extract more then one image from a string containing many images?

    I have yet to find a script that can work with all img tag syntax’s!

    Thanks

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.