How to use a static method as the callback parameter in preg_replace_callback()?

10,248

Solution 1

In PHP when using a class method as a callback, you must use the array form of callback. That is, you create an array the first element of which is the class (if the method is static) or an instance of the class (if not), and the second element is the function to call. E.g.

class A {
     public function cb_regular() {}
     public static function cb_static() {}
}

$inst = new A;

preg_replace_callback(..., array($inst, 'cb_regular'), ...);

preg_replace_callback(..., array('A', 'cb_static'), ...);

The function you are calling of course has to been visible from within the scope where you are using the callback.

See http://php.net/manual/en/language.pseudo-types.php(dead link), for details of valid callbacks.

N.B. Reading there, it seems since 5.2.3, you can use your method, as long as the callback function is static.

Solution 2

You can do it like this:

return preg_replace_callback($pattern, array("Utilities", "LinksCallback"), $input)

Reference: http://php.net/callback

Solution 3

You can also use T-Regx library:

pattern($pattern)->replace($input)->callback([Utilities::class, 'LinksCallback']);
Share:
10,248
Lee
Author by

Lee

Software Dev.

Updated on June 07, 2022

Comments

  • Lee
    Lee almost 2 years

    I'm using preg_replace_callback to find and replace textual links with live links:

    http://www.example.com
    

    to

    <a href='http://www.example.com'>www.example.com</a>
    

    The callback function I'm providing the function with is within another class, so when I try:

    return preg_replace_callback($pattern, "Utilities::LinksCallback", $input);
    

    I get an error claiming the function doesn't exist. Any ideas?

  • Nahydrin
    Nahydrin almost 13 years
    I don't know about static functions, so the above solution may be correct. But if it's a regular function then use this: return preg_replace_callback( $pattern, array( &$this, "LinksCallback" ), $input );
  • Chris Laplante
    Chris Laplante almost 13 years
    That will definitely work for instances. For static functions, my notation is required. I guess they (Zend) assume that most references to static functions will be those inside static classes.
  • Lee
    Lee almost 13 years
    Yes, the LinksCallback() is static and in the class Utilities. I'll give it a try thanks.
  • Lee
    Lee almost 13 years
    Yes thanks. My code should be correct according to the method PHP.net uses, although their example is similar, they use a regular function - not a class static method. Edit: The problem was simply omitting the static keyword.
  • benmarks
    benmarks over 11 years
    Missed the NB, which was my issue. FYI - if using within a class instance, array($this,'method_name') does the trick.