Replacing RegExp matched data with session data

I am trying to find some keywords in the string and replace them with the value in session corresponding to the specified key name.

I tried:

preg_replace('/\\$S{(.*)}/', $_SESSION['$1'], $datasource_query );

Thanks in advance.

You could use [fphp]preg_replace_callback[/fphp].


<?php
session_start();
$_SESSION['username'] = 'Anthony';

function callback_replace_from_session($match){
    $var = $match[0];
    return array_key_exists($var, $_SESSION) ? $_SESSION[$var] : $var;
}

echo preg_replace_callback(
    '~(username)~i',
    'callback_replace_from_session',
    'Welcome back username.'
); #Welcome back Anthony
?>

Thank you.

Is there any way that we can send another parameter(static value, used to differentiate the value to be replaced with) to the callback function along with the matched element?

Sure, this should do it.


$pattern = '~(?<prefix>\\$[a-z]{1}){(?<varname>[a-z0-9-_.]+)}~i';

It will give you ‘prefix’ and ‘varname’. :wink:

[FONT=monospace]
[/FONT]Array
(
    [0] => $S{username}
    [prefix] => $S
    [1] => $S
    [varname] => username
    [2] => username
)

Thank you, that is one of the solution for my issue. And my question is, whether we can pass any additional parameter to the callback function along with the $match parameter.

What are you wanting to pass?

Actually am writing an anonymous function using create_function. I have declared a variable in the function in which this preg_replace_callback is used. The variable created is not accessible inside the anonymous function. Trying to create a global variable!

You could wrap the whole this up in an object, along the lines of…


<?php
class Replacer
{
    public static $replaced = array();
    
    public static function Replace($match){
        
        $value = array_key_exists($match['varname'], $_SESSION) ? $_SESSION[$match['varname']] : $match[0] ;
        
        array_push(
            self::$replaced,
            array(
                'key'   => $match['varname'],
                'value' => $value
            )
        );
        
        return $value;
    }
}

echo preg_replace_callback(
    '~(?<prefix>\\$[a-z]{1}){(?<varname>[a-z0-9-_.]+)}~i',
    array('Replacer', 'Replace'),
    'Welcome $S{username}.'
);  #Welcome Anthony.

print_r(
    Replacer::$replaced
);

/*
    Array
    (
        [0] => Array
            (
                [key] => username
                [value] => Anthony
            )
    
    )
*/