note 26736 modified in function.preg-replace-callback by ronabop

From: Date: Sat, 09 Aug 2003 21:10:07 +0000
Subject: note 26736 modified in function.preg-replace-callback by ronabop
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-53760@lists.php.net to get a copy of this message
The callback function is called once for each match, and should return the replacement value for that match. The array passed to the callback function will only have a single element unless you have used ( ) in the match pattern. Example: find keywords introduced by `` and replace with values from table $val $val[bird]='cormorant'; $val[bird2]='shag'; $val[nest]='paper bag'; $sample = 'The common `bird or bird2, lays its eggs in a `nest'; $result = preg_replace_callback('/``(\w+)/', lookup, $sample); echo $sample,"\n<hr>\n",$result; function lookup($items) { global $val; return $val[$items[1]]; #first ( ) in pattern } --was-- Please disregard my above report - I'd misinterpreted my test results :( Apols for misleading anyone, and to save my further embarrassment please could the site editors remove my mistake! The following is correct (I hope). The callback function is called once for each match, and should return the replacement value for that match. The array passed to the callback function will only have a single element unless you have used ( ) in the match pattern. Example: find keywords introduced by `` and replace with values from table $val $val[bird]='cormorant'; $val[bird2]='shag'; $val[nest]='paper bag'; $sample = 'The common `bird or bird2, lays its eggs in a `nest'; $result = preg_replace_callback('/``(\w+)/', lookup, $sample); echo $sample,"\n<hr>\n",$result; function lookup($items) { global $val; return $val[$items[1]]; #first ( ) in pattern } http://www.php.net/manual/en/function.preg-replace-callback.php

« previous php.notes (#53760) next »