【问题标题】:preg_replace_callback function name with parameter in stringpreg_replace_callback 函数名称,字符串中带有参数
【发布时间】:2014-04-05 11:38:41
【问题描述】:

我正在尝试使用preg_replace_callback() 调用任何函数,并将其参数嵌入在字符串中。

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

echo $string; // some text Asd

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

【问题讨论】:

    标签: php regex preg-replace-callback


    【解决方案1】:

    这就是你可以使用它的方式,我添加了一些 cmets 来澄清代码:

    $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。也许也可以降低或做('nothing')。

    【讨论】:

    • 美丽的答案。谢谢你
    • 更进一步,实际上是两步!.. 1) 我想编辑上面的代码来处理像str_replace 这样带有多个参数的函数。 2)最终解决方案将处理函数内部的函数,例如ucfirst(str_replace('_',' ','test_test')) 谢谢:)
    • @StewartMegaw 我想我应该告诉你一些事情:1) 你表现得像个camelion。一次又一次地编辑答案很痛苦2)你真的应该尝试一些东西,表现出一些努力。这不是免费的编码服务3)我建议尝试实现你想要的,如果你失败了,然后发布一个新的问题,你尝试了什么4)我不不知道您是如何提出新要求的,但我会告诉您实施起来很痛苦。您将需要一个递归解决方案,并且可能构建一个健壮的解析器
    • 感谢所有真正有用的回复。如果你做不到就这么说吧:)笑话......你说对了,让我先试试。
    猜你喜欢
    • 2014-04-11
    • 2022-11-18
    • 1970-01-01
    • 2021-02-03
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    相关资源
    最近更新 更多