note 115326 deleted from function.preg-replace-callback by salathe
| From: | salathe@php.net | Date: | Mon, 07 Jul 2014 07:54:12 +0000 |
| Subject: | note 115326 deleted from function.preg-replace-callback by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199871@lists.php.net to get a copy of this message | ||
Note Submitter: ktretyakgm at gmail dot com
----
Improved version function parseTagsRecursive($input) (demonstrated in the example above):
<?php
class Parse {
private
$pattern
,$substitution
;
public function replace_tags_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;
}
else
{
$this->pattern = $pattern ?: $this->pattern;
$this->substitution = $substitution ?: $this->substitution;
}
return preg_replace_callback($this->pattern, array($this, 'replace_tags_recursive'),
$str);
}
public function next_level_replace($str, array $patterns, 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');
return null;
}
foreach($patterns as $key => $pattern)
{
$str = $this->replace_tags_recursive($str, $pattern, $substitutions[$key]);
}
return $str;
}
}
?>
Now, you can do something like this:
<?php
$bbcode = '
[list]
[*]1. first level[/*]
[*]2. first level[/*]
[*][list][*]1. second level[/*]
[*]2. second level[/*]
[/list]
[/*]
[*]3. first level[/*]
[/list]';
$obj = new Parse;
echo $obj->next_level_replace(
$bbcode
,array(
'~\[list]((?:[^[]|\[(?!/?list])|(?R))+)\[/list]~i'
,'~(?:\[\*]((?:[^[]|\[(?!/?\*])|(?R))+)\[/\*][\r\n]*)~i'
)
,array(
'<ul>$1</ul>'
,'<li>$1</li>'
)
);
?>