preg_replace_callback函数名,参数在string中

时间:2014-03-04 05:10:45

标签: php regex preg-replace-callback

我正在尝试使用preg_replace_callback()来调用嵌入字符串中的参数的任何函数。

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

echo $string; // some text Asd

我需要一些关于模式的帮助,还需要如何使用它来完成示例输出。

1 个答案:

答案 0 :(得分:1)

您可以使用它,我添加了一些注释来澄清代码:

$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;
  

输出一些文字名称和SHOUT。也许还可以降低或做(“没事”)。