1

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?

1 Answer 1

1

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 );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Works perfect! I'd tried with use but I miss this: $array[$matches[1]]
@fire How would you do this using a single array, passing array_keys($preg) as the Search param, and array_values($preg) as the callback array? This causes an error: $body = preg_replace_callback (array_keys($preg), function ($matches) use (array_values($preg)) { return ((isset($array[$matches[1]])) ? $array[$matches[1]] : ''); },$body); Example: sandbox.onlinephpfunctions.com/code/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.