Reply to Re: Execute function in preg_replace_callback with matches and an extra param?

Your name:

Reply:


Posted by Csaba Gabor on 11/19/07 14:01

Poster asks how to pass an additional parameter to callback function in preg_replace_callback.
Instead of preg_replace_callback it may be feasible to use preg_replace. Here's an example showing parameter
passing (watch the wrapping - 5 lines total):

function xslashify($string, $safeChars = "0-9A-Za-z'\\\\0\"") {
// escape all but the safe characters
$string = str_replace(array("\\", "\x0", '"', "'"),
array('\x5c', '\x00', '\x22', '\x27'), $string);
return preg_replace ("/[^$safeChars]/e",
"'\\x' . substr('00' . dechex(ord('$0')),-2)", $string); }



To use poster's own setup as a model, the following will put an apostrophe after each vowel:

$param = "\\'";
$test = preg_replace ('/[aeiou]/ie',
"my_function(array('$0'), '$param')",
"Example string");
function my_function ($aMatches, $param = "^") {
return "$aMatches[0]$param"; }
print $test;


Another option is to have a global variable,
and the callback could make use of that.

Csaba Gabor from Vienna

Marc Bauer wrote:
> Hi
>
> i have an preg_replace_callback that matches some strings and i'd like to
> execute a sub function with two params. Only thing i need is to call the
> subfunction 'my_function' with the $matches and an addition $param. How can
> i add the second param to the preg_replace_callback line?
>
>
> function test_function($demo) {
> $example = "Some data";
> $test = preg_replace_callback('my example regexp', 'my_function',
> $example);
> }
>
> function my_function($matches, $param = 0) {
> //do some stuff here
> if ($param) {
> // do something special
> }
> }
>
>
> Regards
> Marc

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация