06/10/2010 1:53pm

PHP | Working Example - ContentParser example


<?php


/**
* Replaces Images to a predefined max width and adds a nyroModal class to the image
* In template use : $Content.Parse(ArticleImageParser)
*/

class ArticleImageParser extends TextParser{

public function parse() {

// match image src
$pattern = '/<img[^>]+src[\\s=\'"]';
$pattern .= '+([^"\'>\\s]+)/is';
if(preg_match_all($pattern,$this->content,$match)){
$i = 0;
foreach ($match[0] as $m){
//var_dump($m); //"<img class="right" src="assets/Articles/installingsilverstripe/wampserver.jpg"

// get original image url
$href = preg_replace('/_resampled\/resizedimage[0-9]*-/', '', $match[1][$i]);
// add a tag with original image url
$this->content = str_replace ($m,'<a class="nyroModal" href="'.$href.'">'.$match[0][$i],$this->content);
$i++;
}

// add missing </a> tag after each image
$this->content = preg_replace('/<img[^>]+>/', '${0}</a>', $this->content);
}

return $this->content;
}
}


Post Comment