Question

I'm migrating an application to work with PHP 5.5, and I need to remove the /e character from the preg_replace function, to do that I'm using preg_replace_callback()

My actual function looks like this:

preg_replace ( '#\{([a-z0-9\-_]*?)\}#Ssie' , '( ( isset($array[\'\1\']) ) ? $array[\'\1\'] : \'\' );' , $template );

Where:

$template contains a html document with tags like this one: {user_name}

and $array contains

$array['user_name'] = 'The user';

I've been trying to convert this to work with PHP 5.5 with not success.

This is what I did so far:

return preg_replace_callback ( '#\{([a-z0-9\-_]*?)\}#Ssi' , function ( $array ) {
    return ( ( isset ( $array[1] ) ) ? $array[1] : '' );
} , $template );

But It's not working. The tags closed in braces are not being replaced.

What Am I missing?

Was it helpful?

Solution

You need to use the use keyword to pull in $array into your anonymous function...

return preg_replace_callback ( '#\{([a-z0-9\-_]*?)\}#Ssi' , function ($matches) use ($array) {
    return ( ( isset ( $array[$matches[1]] ) ) ? $array[$matches[1]] : '' );
} , $template );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top