Created
November 14, 2009 18:08
-
-
Save laszlokorte/234665 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 Bbcode { | |
const RES_STRING = 0; | |
const RES_FUNC_OBJECT = 1; | |
const RES_FUNC_NAME = 2; | |
const POS_START_KEY = 'start'; | |
private static $patterns = array(); | |
private static $patterns_count=0; | |
private $pattern; | |
private $type; | |
private $action; | |
public static function replace($string) | |
{ | |
for($i=0; $i<self::$patterns_count; $i++) | |
{ | |
$string = self::$patterns[$i]->apply($string); | |
} | |
return $string; | |
} | |
public static function clear($string) | |
{ | |
for($i=0; $i<self::$patterns_count; $i++) | |
{ | |
$string = self::$patterns[$i]->filter($string); | |
} | |
return $string; | |
} | |
public function __construct($pattern, $action, $pos = 'end') | |
{ | |
$this->pattern = $pattern; | |
$this->action = $action; | |
if(is_object($action)) | |
{ | |
$this->type = self::RES_FUNC_OBJECT; | |
} | |
elseif(is_string($action)) | |
{ | |
if(strstr($action, 'return')) | |
{ | |
$this->action = create_function('$match',$this->action); | |
$this->type = self::RES_FUNC_OBJECT; | |
} | |
elseif(substr ($action, -2 ) === '()') | |
{ | |
$this->type = self::RES_FUNC_NAME; | |
} | |
else | |
{ | |
$this->type = self::RES_STRING; | |
} | |
} | |
if($pos==self::POS_START_KEY) | |
{ | |
array_unshift(self::$patterns, $this); | |
} | |
else | |
{ | |
array_push(self::$patterns, $this); | |
} | |
self::$patterns_count += 1; | |
} | |
private function apply($string) | |
{ | |
switch($this->type) | |
{ | |
case self::RES_STRING: | |
$string = preg_replace($this->pattern, $this->action, $string); | |
break; | |
case self::RES_FUNC_OBJECT: | |
case self::RES_FUNC_NAME: | |
$string = preg_replace_callback($this->pattern, $this->action, $string); | |
} | |
return $string; | |
} | |
private function filter($string) | |
{ | |
return preg_replace($this->pattern, "$1", $string); | |
} | |
} | |
new Bbcode("/\[b\](.*?)\[\/b\]/si","<strong>$1</strong>"); | |
new Bbcode("/\[i\](.*?)\[\/i\]/si","<em>$1</em>"); | |
new Bbcode("/\[u\](.*?)\[\/u\]/si","<span style=\"text-decoration: underline;\">$1</span>"); | |
$string = '[b]Ich[/b] [i]heisse[/i] [u]Peter[/u]'; | |
echo Bbcode::replace($string); | |
# <strong>Ich</strong> <em>heisse</em> <span style="text-decoration: underline;">Peter</span> | |
echo Bbcode::clear($string); | |
# Ich heisse Peter | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment