Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class Abcode {
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 Abcode("/\[b\](.*?)\[\/b\]/si","<strong>$1</strong>");
new Abcode("/\[i\](.*?)\[\/i\]/si","<em>$1</em>");
new Abcode("/\[u\](.*?)\[\/u\]/si","<span style=\"text-decoration: underline;\">$1</span>");
$string = '[b]Ich[/b] [i]heisse[/i] [u]Peter[/u]';
echo Abcode::replace($string);
# <strong>Ich</strong> <em>heisse</em> <span style="text-decoration: underline;">Peter</span>
echo Abcode::clear($string);
# Ich heisse Peter
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.