note 115328 deleted from function.preg-replace-callback by ktretyak
| From: | ktretyak@php.net | Date: | Mon, 29 Sep 2014 09:32:08 +0000 |
| Subject: | note 115328 deleted from function.preg-replace-callback by ktretyak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-200543@lists.php.net to get a copy of this message | ||
Note Submitter: ktretyakgm at gmail dot com
----
I think now I have written a class for full parsing, in particular, bbcode. Parsing is carried out
by using preg_replace_callback ().
This class allows you to break apart complex nested structures code.
<?php
/**
* @author ÐоÑÑÑ Ð¢ÑеÑÑк
*/
class Parse {
private
$patterns
,$substitutions
,$pattern
,$substitution
;
/**
* @param mix $str
* @param string $pattern
* @param string $substitution
* @return string
*/
protected function replace_recursive($str, $pattern = null, $substitution = null)
{
if (is_array($str))
{
unset($str[0]);
$tmp = $this->substitution;
foreach($str as $key => $match)
{
$tmp = str_replace('$'.$key, $match, $tmp);
}
$str = $tmp;
if ( !empty($this->patterns))
{
$obj = new Parse;
$str = $obj->next_level($str, $this->patterns, $this->substitutions);
}
}
else
{
$this->pattern = $pattern ?: $this->pattern;
$this->substitution = $substitution ?: $this->substitution;
}
return preg_replace_callback($this->pattern, array($this, 'replace_recursive'),
$str);
}
/**
* @param string $str
* @param mix $patterns
* @param mix $substitutions
* @return string
*/
public function next_level($str, $patterns, $substitutions)
{
$this->compare_params($patterns, $substitutions);
$this->patterns = $patterns;
$this->substitutions = $substitutions;
return $this->replace_recursive($str, array_shift($this->patterns),
array_shift($this->substitutions));
}
/**
* @param mix $patterns
* @param mix $substitutions
* @throws Exception
*/
protected function compare_params( & $patterns, & $substitutions)
{
$patterns = (array) $patterns;
$substitutions = (array) $substitutions;
if (count($patterns) != count($substitutions))
{
throw new Exception('The number of elements in the $substitutions array must equal the
number of elements in the $patterns array');
}
}
/**
* @param string $str
* @param mix $patterns
* @param mix $substitutions
* @return string
*/
public function replace_tags($str, $patterns, $substitutions)
{
$this->compare_params($patterns, $substitutions);
foreach($patterns as $key => $pattern)
{
$str = $this->next_level($str, $pattern, $substitutions[$key]);
}
return $str;
}
}
?>
Examples of use can be viewed on https://gist.github.com/KostyaTretyak/4a9dc3490db73234f956
(Preview my comment http://php.net/manual/en/function.preg-replace-callback.php#115326
can be removed, as it is the best code)