0
votes

This code:

$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                            create_function(
                                  '$matches',
                                  'return $matches[1] + $t;'
                            ), $func);

How to make $t visible from create_function() in preg_replace() function?

5
You should use closures instead php.net/functions.anonymous function($matchtes)use($t){/*..*/} - KingCrunch
@hakre "1" + 100 ;) But I see, what you mean: The regular expression matches something starting with Name, thus the function will always return 100 (=$t). Probably not wanted. - KingCrunch
The solution depends on what version of PHP you are using. Ideally, the solution is to use a closure passing in the $t variable to the use construct. This requires at least PHP 5.3. BTW, if the value of $t doesn't every change, you might consider using a constant which will be available in any context. - Wil Moore III

5 Answers

3
votes

An anonymous function would work, while making use of the use syntax:

$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
    function($matches) use($t) // $t will now be visible inside of the function
    {
        return $matches[1] + $t;
    }, $func);
2
votes

You can't make the variable accessible, but in your case you can just use the value:

$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                            create_function(
                                  '$matches',
                                  'return $matches[1] + ' . $t .';'
                            ), $func);

However, it is highly recommended you use the function($matches) use ($t) {} syntax here (http://php.net/functions.anonymous).

And there is eval modifier for preg_replace:

$str = preg_replace("/(Name[A-Z]+[0-9]*)/e", '$1+'.$t, $func);

But I have the feeling that your function is using the wrong operator here anyway - or the wrong pattern / subpattern.

0
votes

Same way you make any function see a global variable.

$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                            create_function(
                                  '$matches',
                                  'global $t; return $matches[1] + $t;'
                            ), $func);
0
votes

You can use $GLOBALS but its not highly recomended ...

$str = preg_replace_callback ( "/(Name[A-Z]+[0-9]*)/", create_function ( '$matches', 'return $matches[1] + $GLOBALS["t"];' ), $func );

Better Solution

http://php.net/functions.anonymous anonymous function .. if you don't like to use that you can also do array_walk ( http://php.net/manual/en/function.array-walk.php ) after you have gotten the result in an array format then pass $t as a proper function argument

0
votes

in anonymous just use the keyword use or global in create_function use global

function() use($var1,$var2...etc){code here}

or

create_func($args,'global $var1,$var2;code here;');