1

In PHP

I'm converting a large number of blog posts into something more mobile friendly. As these blogs posts seem to have alot of large images in them, I would like to use some regex or something to go thorugh the article's HTML and replace any images that aren't currently linked with a link to that image. This will allow the mobile browser to display the article without any images, but a link to the image inplace of where the image would be thus downsizing the page download size.

Alternatively, if anyone knows any php classes/functions that can make the job of formatting these posts easier, please suggest.

Any help would be brilliant!

David
  • 4,717
  • 8
  • 35
  • 46
  • *(related)* [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon Oct 24 '11 at 09:19
  • possible duplicate of [How can I use XPath and DOM to replace a node/element in php?](http://stackoverflow.com/questions/4614434/how-can-i-use-xpath-and-dom-to-replace-a-node-element-in-php) – Gordon Oct 24 '11 at 09:25

3 Answers3

0

To parse HTML, use an HTML parser. Regex is not the correct tool to parse HTML or XML documents. PHP's DOM offers the loadHTML() function. See http://in2.php.net/manual/en/domdocument.loadhtml.php. Use the DOM's functions to access and modify img elements.

Sudheer
  • 710
  • 6
  • 25
0

How about doing it in JQuery instead of PHP. That way, it will work across different blogging software.

You can do something like...

$(document).ready( function () {
    $('#content img').each(function () {
        var imageUrl = $(this).attr('src');
        //* Now write codes to delete off the image and put in a link instead. :)
    });
});
iWantSimpleLife
  • 1,944
  • 14
  • 22
0

With Regexp something like this:

$c = 0;
while(preg_match('/<img src="(.*?)">/', $html, $match) && $c++<100) {
  $html = str_replace($match[0], '<a href="'.$match[1].'">Image '.$c.'</a>');
}

You can also use preg_replace (saves the loop), but the loop allows for easy extensions, e.g. using the image functions to create thumbnails.

nullmark
  • 86
  • 2