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

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

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏