Page 1 of 1

stuck with bbtag replacement function

Posted: Fri Mar 03, 2006 4:17 pm
by s.dot

Code: Select all

function replaceIMGTags($text){
		
	preg_match_all("#[img](.+?)[/img]#ism",$text,$matches);
	$links = array();
	foreach($matches[1] AS $link){
		$links[] = trim(strip_tags($link));
	}
	preg_replace($matches[1],$links,$matches);
	
}
That's what I have so far. I'm attempting to find text inbetween [ img ] and [ /img ] tags, then trim and strip_tags() on that link, then replace it in the $text

Am I on the right track? after I replace the $matches[1] with the "cleaned" links, how do I go about inserting the image code into the $text?

Hope I made sense.

Posted: Fri Mar 03, 2006 4:31 pm
by s.dot
after digging around a little bit I came up with this

Code: Select all

function replaceIMGTags($text){
		
		preg_replace("#[img](.+?)[/img]#ism","<img src=\"".trim(strip_tags('\\1'))."\" alt=\"Image\">",$text);

}
However I can't find the correct way to concatenate the trim(strip_tags()) part in there, and successfully use the $1 extracted from the regex

any help please? :P

Posted: Fri Mar 03, 2006 4:33 pm
by feyd
research the e modifier, however, it's dangerous. I'd suggest using preg_replace_callback() instead.

Posted: Fri Mar 03, 2006 4:44 pm
by s.dot
i looked at the e pattern modifier
how is it dangerous? (it seems to be a simple solution)

Posted: Fri Mar 03, 2006 4:48 pm
by feyd
it can open your function to injection attacks.

Posted: Fri Mar 03, 2006 9:49 pm
by s.dot
K, so I think I finally got it.
I Think that this properly cleans links that are to be put inside of an image.
Please let me know if this is subject to injection or abuse or whatever

Code: Select all

<?php

function replaceIMGTags($text){
		
	$text = preg_replace_callback('#\[img\](.+?)\[/img\]#im',
		create_function(
		'$matches',
			'return \'<img src="\'.trim(htmlentities($matches[1],ENT_QUOTES)).\'" alt="Image">\';'
		),
	$text);
	return $text;
		
}



$body = "this is an [img]http://www.domain.com/image1.jpg[/img]\n\r\n
and another [img]http://domain.com/image2.jpg[/img] that's on \n\r\n\n\n\n
separate lines";

echo htmlentities(replaceIMGTags($body));
?>
This returns:

Code: Select all

this is an <img src="http://www.domain.com/image1.jpg" alt="Image"> and another <img src="http://domain.com/image2.jpg" alt="Image"> that's on separate lines