Re: preg_replace_callback()

From: Date: Mon, 10 Sep 2001 10:10:53 +0000
Subject: Re: preg_replace_callback()
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-66713@lists.php.net to get a copy of this message
ceo@l-i-e.com (Richard Lynch) writes: > A "callback" is when you execute a function, and you provide to it a name of > *another* function, which it will call on some data in the middle of its > task. > > It's a very handy way to provide extreme flexibility in functional > languages. > > For example: > > function my_array_walk($array, $function){ > while (list($k, $v) = each($array)){ > # Here's the magic that implements a 'callback' > $function($k, $v); > } > } > > function your_echo($key, $value){ > echo "$key $value<BR>\n"; > } > > $foo = array('a'=>1, 'b'=>2, 'c'=>3); > > my_array_walk($foo, 'your_echo'); > > This rather silly example will "walk" the array and call 'your_echo' on > each > key/value pair. > > Dunno exactly how preg_ uses it though... It calls the callback function for each match, passing it an array. The matching string is replaced by whatever the callback function returns. Here's a fairly pointless example of names and email addresses being replaced by mailto links with a bit of extra processing on their name... -robin <?php function mailto( $match ) { // match[0] contains the complete matched string. // match[1] contains the first parenthesised subpattern. // match[2] contains the second parenthesised subpattern. // etc... $match[1] = strrev($match[1]); return "<a href=\"mailto:{$match[2]}\">{$match[1]}</a>"; } $testString =<<<EOS "John Smith" <johns@foo.co.uk> "Tommy Atkins" <tatkins@bar.mil> "Davey Jones" <djones@baz.com> EOS; $outputString = preg_replace_callback('/"(.+?)"\s*<(.+?)>/', 'mailto', $testString); print "<pre> $outputString </pre>"; ?>

« previous php.general (#66713) next »