Created
October 11, 2009 20:21
-
-
Save laszlokorte/207854 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ClansphereAbcode { | |
# alle registered patter | |
private static $patterns = array(); | |
public static function convert($string, $options = array()) { | |
$string = self::secure($string); | |
foreach(self::$patterns AS $pat => $func) { | |
$string = preg_replace_callback($pat, $func, $string); | |
} | |
return $string; | |
} | |
public static function secure($string) { | |
$string = htmlentities($string, ENT_QUOTES, 'UTF-8'); | |
return $string; | |
} | |
public static function register_pattern($pat, $function) { | |
if(!isset(self::$patterns[$pat])) { | |
if(is_string($function)) { | |
if(preg_match('/return/',$function)>0) | |
self::$patterns[$pat] = create_function('$match',$function); | |
else | |
self::$patterns[$pat] = $function; | |
} | |
elseif(is_object($function)) | |
self::$patterns[$pat] = $function; | |
} | |
} | |
public static function remove_pattern($pat) { | |
if(isset(self::$patterns[$pat])) | |
unset(self::$patterns[$pat]); | |
} | |
} | |
# three ways to register a pattern: | |
# anonymous function as string | |
ClansphereAbcode::register_pattern('=\[b\](.*?)\[/b\]=si', 'return "<b>" . $match[1] . "</b>";'); | |
ClansphereAbcode::register_pattern('=\[u\](.*?)\[/u\]=si', 'return "<u>" . $match[1] . "</u>";'); | |
# anonymous function as object (php5.3?) | |
ClansphereAbcode::register_pattern('=\[i\](.*?)\[/i\]=si', function($match) {return "<i>" . $match[1] . "</i>" ;}); | |
# function by name | |
class MyClansphereAddon { | |
public static function crazy($string) { | |
return $string[1] . ' IS CRAZY!!'; | |
} | |
} | |
ClansphereAbcode::register_pattern('=\[cr\](.*?)\[/cr\]=si', 'MyClansphereAddon::crazy'); | |
# you can also remove a pattern | |
ClansphereAbcode::remove_pattern('=\[b\](.*?)\[/b\]=si'); | |
# let's use it | |
$string = '<div>[u]underlined[/u][b]bold[/b][i]italic[/i]</div>[cr]Peter[/cr]'; | |
$string = ClansphereAbcode::convert($string); | |
echo $string; | |
# output: <div>underlined[b]bold[/b]italic</div>Peter IS CRAZY!! | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment