Archive for June, 2009

Enhancing wordpress themes with regular expressions

June 22, 2009

I’ve been using wordpress quite a bit lately, and didn’t seem to be able to do something I wanted within the confines of a regular wordpress theme. Regular expressions came to the rescue – you can just use them in your theme and plugin files to do more-or-less anything you want with the content.

Here’s how I extracted the images so that they weren’t displayed within the post but instead in another div separate from the post text:

$images = ""; $matches = array();
if (preg_match_all("/(<img[^>]*>)/iUs",$content,$matches)) {
    $images = implode(" ",$matches[1]);
    $content = preg_replace("/<img[^>]*>/iUs","",$content);
$content = "<div class=\"text\">$content</div>".
           "<div class=\"images\">$images</div>\n";

See what I did? I grabbed all the image tags out of $content with preg_match_all(), put them all into the variable $images, and then got rid of them all in $content using preg_replace(). Then I displayed $content and $images in separate divs.

You can use it on a page level too – on the index.php page of a theme, say, you can do an ob_start() to buffer the content, then ob_get_clean() it into a variable and manipulate the variable with regular expressions before echoing it out. So, for example, you could extract all the images or links (or whatever) from the content and display them somewhere else on the page.