note 109074 modified in function.preg-replace-callback by danbrown

From: Date: Tue, 19 Jun 2012 13:45:24 +0000
Subject: note 109074 modified in function.preg-replace-callback by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-188693@lists.php.net to get a copy of this message
From PHP 5.3 you can use an anonymous function to pass local variables into the callback.&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;&#13;&#10;public function replace_variables( $subject, $otherVars ) {&#13;&#10; $linkPatterns = array(&#13;&#10; &#39;/(&#60;a .*)href=(&#34;)([^&#34;]*)&#34;([^&#62;]*)&#62;/U&#39;,&#13;&#10; &#34;/(&#60;a .*)href=(&#39;)([^&#39;]*)&#39;([^&#62;]*)&#62;/U&#34;&#13;&#10; );&#13;&#10;&#13;&#10; $callback = function( $matches ) use ( $otherVars ) {&#13;&#10; $this-&#62;replace_callback($matches, $otherVars);&#13;&#10; };&#13;&#10;&#13;&#10; return preg_replace_callback($this-&#62;patterns, $callback, $subject);&#13;&#10;}&#13;&#10;&#13;&#10;public function replace_callback($matches, $otherVars) {&#13;&#10; return $matches[1] . $otherVars[&#39;myVar&#39;];&#13;&#10;}&#13;&#10;?&#62; --was-- From PHP 5.3 you can use an anonymous function to pass local variables into the callback. <?php public function replace_variables( $subject, $otherVars ) { $linkPatterns = array( '/(<a .*)href=(")([^"]*)"([^>]*)>/U', "/(<a .*)href=(')([^']*)'([^>]*)>/U" ); $callback = function( $matches ) use ( $otherVars ) { $this->replace_callback($matches, $otherVars); }; return preg_replace_callback($this->patterns, $callback, $subject); } public function replace_callback($matches, $otherVars) { return $matches[1] . $otherVars['myVar']; } http://php.net/manual/en/function.preg-replace-callback.php

« previous php.notes (#188693) next »