customized image tags
Posted on: 14 Oct, 2009
Read more in notebook: programming bits
As you probably know I've moved and redesigned my website several times since it's original inception and one thing I quickly decided is that it's no good putting real image tags right into my blog posts because then if (or let's face it when) I redesign my website I have to troll through all the posts wrapping the images in html tags or changing them into links for a gallery, or removing the links, or whatever new idea seems desirable at the time. Instead I've replaced the html image tag with a tag of my own. Not to surprisingly this too has gone through several versions but I'm quite proud of the current one and I even wrote proper regular expressions rather than the slightly dubious and a bit hacked together parsing solution I had previously. My current tag looks like this: <my_img id=999>
My parsing code is rather simple, I just go through each my_image tag and replace it with a proper html image tag after retrieving the image name from the database based on it's id. I probably could change it to access the database once for all images but since my posts rarely have more than a few images this seems hardly worth the extra complication.
function replaceImgTags($string) {
$db = new MySQlImageConnector();
$found = true;
$regExpr = '/<[ ]*my_img[ ]+id=\"(\d+)\"[ ]*\/>/';
$matches;
preg_match_all($regExpr, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $matchSet) {
$loc1 = stripos($string, $matchSet[0]);
$size = strlen($matchSet[0]);
$image = $db->getImageById((int)$matchSet[1]);
$tag = "<p><img src=\"".CB_IMAGE.$image->getFileName()."\"";
$tag .= " alt=\"".$image->getName()."\" /></p>";
$string = substr($string, 0, $loc1).$tag.substr($string, $loc1+$size);
}
return $string;
}
While I was writing this post I discovered that I don't have a good way of formatting code snipits in my blog and I don't really want to have to hand format each one individually so I added a <my_code> tag with a processor to replace the newlines and spaces and wrap it in a paragraph with a css style.
function replaceCodeBlockTags($string){
$found = true;
$reg ='/<[ ]*my_code[ ]*>(.*?)<[ ]*\/[ ]*my_code[ ]*>/s';
$matches;
preg_match_all($reg, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $matchSet) {
$match = $matchSet[1];
$loc1 = stripos($string, $match);
$size = strlen($match);
//keep all the special characters
$match = htmlentities($match);
//replace newlines with breaks
$match = str_replace("\n", "<br />", $match);
//replace tabs with a bunch of spaces
$match = str_replace(" ", " ", $match);
$match = "<p class=\"code\">".$match."</p>";
$string = substr($string, 0, $loc1).$match.substr($string, $loc1+$size);
}
return $string;
}