preg_match_callback and callbacks

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

   I've never really wrapped my mind around preg_match_callback, and
reading the manual leaves me more confused.

   I'd like to call a function and pass in the matches and one other

$content = preg_replace_callback(


function replaceAFragment($match,$D){


Now, that doesn't work, but it is as close as I've come, and I can more
less understand why it doesn't work. I'd rather not have $D as a global
and take the easy way out.

   I don't really understand how the matches get passed in, but I know
that it works. It's all soooo confusing. I've got a much better
understanding of how to do this with classes.


Re: preg_match_callback and callbacks

Jeff Thies wrote:

Quoted text here. Click to load it


You can?

Quoted text here. Click to load it

You do not have $D as a global variable here.  It is a *local* variable in
the dynamically created function and in replaceAFragment().

Quoted text here. Click to load it

I think it is well-documented by the examples in the manual.  The callback
gets passed *one* argument that is the match.  It is an array that has the
entire match as element with key 0, and capturing parenthesized
subexpression matches as elements with keys 1, 2, aso.


Quoted text here. Click to load it

With your code you should see a warning:

$ php -r 'echo preg_replace_callback("/\[(.*?)\]/s",
create_function("$match,$D", "print_r($match); return $match[1];"),
PHP Warning:  Missing argument 2 for __lambda_func() in Command line code(1)
: runtime-created function on line 1
    [0] => [a]
    [1] => a

$ php -v
PHP 5.3.2-1 with Suhosin-Patch (cli) (built: Mar 13 2010 22:18:25)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Zend Debugger v5.2, Copyright (c) 1999-2009, by Zend Technologies
    with Suhosin v0.9.31, Copyright (c) 2007-2010, by SektionEins GmbH

Quoted text here. Click to load it

It is (slightly) harder to do with classes, so I don't see your problem.

Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
  -- from < (404-comp.)

Site Timeline