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.

HamZa
  • 14,671
  • 11
  • 54
  • 75
Stewart Megaw
  • 311
  • 2
  • 14

1 Answers1

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
  • 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 :) – Stewart Megaw Mar 05 '14 at 00:20
  • @StewartMegaw I think I should tell you something: **1)** You're acting like a [camelion](http://meta.stackexchange.com/questions/43478). 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 – HamZa Mar 05 '14 at 10:09
  • Thanks for that all the really useful response. If you cant do it just say so :) Jokes... you correct let me try first. – Stewart Megaw Mar 06 '14 at 01:01