Search code examples
phpregexpreg-replace-callback

preg_replace_callback function name with parameter in string


I am trying to use preg_replace_callback() to call any function with its parameter(s) embedded in a string.

$string = "some text ucfirst('asd')";
$pattern = "~ucfirst([a-z]+)\(\)~";
$string = preg_replace_callback($pattern, "ucasef", $string);

echo $string; // some text Asd

I need some help with the pattern but also with how to use it to accomplish the example output.


Solution

  • This is how you may use it, I've added some comments to clarify the code:

    $input = "some text ucfirst('name') and strtoupper (\"shout\"  ). Maybe also make it strtolower(   'LOWER') or do('nothing').";
    
    $pattern = '~
    (\w+)      # Match the function name and put it in group 1
    \s*\(\s*   # Some optional whitespaces around (
    ("|\')     # Match either a double or single quote and put it in group 2
    (.*?)      # Match anything, ungreedy until ...
    \2         # Match what was matched in group 2
    \s*\)      # Some optional whitespaces before )
    ~xs';      # XS modifiers, x to make this fancy formatting/commenting and s to match newlines with the dot "."
    
    $output = preg_replace_callback($pattern, function($v){
        $allowed = array('strtolower', 'strtoupper', 'ucfirst', 'ucwords'); // Allowed functions
        if(in_array(strtolower($v[1]), $allowed)){ // Check if the function used is allowed
            return call_user_func($v[1], $v[3]); // Use it
        }else{
            return $v[0]; // return the original value, you might use something else
        }
    }, $input);
    
    echo $output;
    

    Output: some text Name and SHOUT. Maybe also make it lower or do('nothing').