dtjwov4984 2014-03-04 05:10
浏览 28
已采纳

preg_replace_callback函数名,参数在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.

  • 写回答

1条回答 默认 最新

  • douba8048 2014-03-04 06:21
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请提供一个符合要求的网页链接。
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码