Forum Moderators: coopster

Message Too Old, No Replies

preg_replace_callback() to call a function in the same class

         

andytwiz

3:47 pm on Apr 2, 2005 (gmt 0)

10+ Year Member



Hi

Im using preg_replace_callback() to try to call a function within the same class:

e.g.

[code]
class a {

function a() {
preg_replace_callback($reg_ex, "b", $text);
}

function b() {
// This is the call back function I want to call from preg_replace_callback
}

}

I've tried putting the callback function as "b", "a::b", "this->b" but no luck. how do i call a callbackfunction from within the same class?

Cheers

coopster

12:17 am on Apr 13, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The answer is found after studying and understanding the callback [php.net] type. You are going to run into this a lot with classes, so you may want to get your head around it. Read that link, as well as call_user_func() [php.net]. I'll throw in an example using your class, but a bit of the code from the PHP preg_replace_callback() [php.net] page. Pay special attention to the bolded parameter...
<?php 
class a {
function a($text)
{
echo preg_replace_callback("¦(\d{2}/\d{2}/)(\d{4})¦", array(&$this, 'b'), $text);
}
function b(&$matches)
{
return $matches[1].($matches[2]+1);
}
}
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
$var = new a($text);
?>
If you copy and paste this to test, don't forget to replace the broken pipe (¦) symbol by rekeying it as the forum breaks the pipe symbol.

andytwiz

4:07 pm on Apr 13, 2005 (gmt 0)

10+ Year Member



great thanks!

do you know if its possible to supply my own arguments along with matches to the function?

coopster

7:26 pm on Apr 13, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Not through the parameter list as that is internal to the workings of preg_replace_callback(). You can, of course, use logic within the function and apply your arguments that way, including use of GLOBAL variables.

I noticed I left an unnecessary reference in there too, no need for the ampersand sign on the second function parameter, $matches:

function b($matches)

andytwiz

7:32 pm on Apr 13, 2005 (gmt 0)

10+ Year Member



thanks that's what i've been doing.