note 115326 added to function.preg-replace-callback

From: Date: Sun, 06 Jul 2014 02:33:00 +0000
Subject: note 115326 added to function.preg-replace-callback
Groups: php.notes 
Request: Send a blank email to php-notes+get-199862@lists.php.net to get a copy of this message
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>' ) ); ?> ---- Server IP: 72.52.91.14 Probable Submitter: 78.111.187.149 ---- Manual Page -- http://php.net/manual/en/function.preg-replace-callback.php Edit -- https://master.php.net/note/edit/115326 Del: integrated -- https://master.php.net/note/delete/115326/integrated Del: useless -- https://master.php.net/note/delete/115326/useless Del: bad code -- https://master.php.net/note/delete/115326/bad+code Del: spam -- https://master.php.net/note/delete/115326/spam Del: non-english -- https://master.php.net/note/delete/115326/non-english Del: in docs -- https://master.php.net/note/delete/115326/in+docs Del: other reasons-- https://master.php.net/note/delete/115326 Reject -- https://master.php.net/note/reject/115326 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199862) next »