0

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.

1 Answer 1

1

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').

Sign up to request clarification or add additional context in comments.

3 Comments

To go one step further, actually two steps!.. 1) I would like to edit the code above to handle functions such as str_replace which take multiple arguments. 2) And a final solution would handle functions inside functions such as ucfirst(str_replace('_',' ','test_test')) Thanks :)
@StewartMegaw I think I should tell you something: 1) You're acting like a camelion. It's a pain to edit the answer again and again 2) You should really try something, show some efforts. This isn't a free coding service 3) I suggest to try to implement what you want if you fail then post a new question with what you have tried 4) I don't know how you came with the new requirements but I will tell you it's a pain to implement. You will need a recursive solution and maybe build a robust parser
Thanks for that all the really useful response. If you cant do it just say so :) Jokes... you correct let me try first.

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.