Page 1 of 1

PHP Challange - Make a BBCode parser

Posted: Mon Oct 25, 2010 2:37 pm
by InsanityNet
My challange to you is to make a bbcode parse in less than 1KB
The following lines are excluded, and implied. Do not submit with your enties:

Code: Select all

<?php
function bbcode($str) {
and

Code: Select all

return $str;
}
?>
You must have, underline, bold, italicized, url, image, color, and strikethoru

Re: PHP Challange - Make a BBCode parser

Posted: Tue Oct 26, 2010 12:07 am
by requinix
1KB is a lot.

Wrote something at about 900 bytes. Proper HTML. Requires PHP 5.3.
Here's the minified version - 525 bytes.

Code: Select all

$t=array(array("u","","<span style=\"text-decoration: underline;\">%s</span>"),array("b","","<strong>%s</strong>"),array("i","","<em>%s</em>"),array("img","","<img src=\"%s\" alt=\"\" />"),array("color","=(#?[0-9a-z]+)","<span style=\"color: %s\">%s</span>"),array("s","","<span style=\"text-decoration: line-through;\">%s</span>"));$c=function($m)use(&$u){$f="htmlentities";return sprintf($u[2],$f($m[1]),$f($m[2]));};foreach($t as $u)$str=preg_replace_callback($n="~\[$u[0]$u[1]\](.*?)\[/$u[0](\])~is",$c,$str);return $str;
I could reduce it even further but I think the point has been made just fine.

Insert the usual stuff about file size versus readability and such here.

Re: PHP Challange - Make a BBCode parser

Posted: Tue Oct 26, 2010 10:56 am
by InsanityNet
Hi, this entrie is invalid because urls do not work, and nesting of the fails.

Re: PHP Challange - Make a BBCode parser

Posted: Tue Oct 26, 2010 12:15 pm
by John Cartwright
tasairis wrote:1KB is a lot.

Wrote something at about 900 bytes. Proper HTML. Requires PHP 5.3.
Here's the minified version - 525 bytes.

Code: Select all

$t=array(array("u","","<span style=\"text-decoration: underline;\">%s</span>"),array("b","","<strong>%s</strong>"),array("i","","<em>%s</em>"),array("img","","<img src=\"%s\" alt=\"\" />"),array("color","=(#?[0-9a-z]+)","<span style=\"color: %s\">%s</span>"),array("s","","<span style=\"text-decoration: line-through;\">%s</span>"));$c=function($m)use(&$u){$f="htmlentities";return sprintf($u[2],$f($m[1]),$f($m[2]));};foreach($t as $u)$str=preg_replace_callback($n="~\[$u[0]$u[1]\](.*?)\[/$u[0](\])~is",$c,$str);return $str;
I could reduce it even further but I think the point has been made just fine.

Insert the usual stuff about file size versus readability and such here.
Post the non-minified version next time :D