【问题标题】:How to pass parameter in preg_replace to a function in PHP? [duplicate]如何将 preg_replace 中的参数传递给 PHP 中的函数? [复制]
【发布时间】:2021-03-02 14:22:12
【问题描述】:

我想做这样的事情:

我有这个字符串:

Lorem ipsum {shortcode 42} dolor sit amet.

我想这样解析:

preg_replace('/\{shortcode (\d+)\}/i', MyClass::myFunction('$1') , $content);

MyClass 代码如下所示:

class MyClass {
    public static function myFunction(string $id) {
        // ...

        return 'hello world';
    }

}

但在myFunction()$id 将始终是$1 字符串,而不是原始$1 的内容,什么是数字。

如何将参数中的 preg_replace 替换值传递给我的函数?

【问题讨论】:

  • “但在 myFunction() 中,$id 将始终是 $1 字符串” - 不仅如此,它会在任何替换之前被 调用甚至发生。如果您将函数 call 指定为另一个函数的参数,则该函数调用会在另一个函数运行之前发生。
  • 我也检查了这个,但结果相同。你能用我的代码给我一个例子吗?我认为这是一件太简单的事情,但我没有看到一些基本的东西......谢谢!
  • 该手册页上有多个示例。

标签: php regex preg-replace


【解决方案1】:

在不重写您的类方法的情况下,使用preg_replace_callback 中的匿名函数调用您的方法,使用索引1 作为第一个捕获组匹配:

$result = preg_replace_callback('/\{shortcode (\d+)\}/i',
                                function($m) {
                                    return MyClass::myFunction($m[1]);
                                }, $content);

或者你可以调用静态方法,但是你需要在那里使用参数的1索引:

// ['MyClass', 'myFunction'] or 'MyClass::myFunction'
$result = preg_replace('/\{shortcode (\d+)\}/i', ['MyClass', 'myFunction'], $content);

class MyClass {
    public static function myFunction(array $array) {
        // use $array[1]

        return 'hello world';
    }

}

【讨论】:

    【解决方案2】:

    使用类的静态方法作为回调的简单示例:

    class MyClass {
        static function myFunction($arg) {
            return "[Hello, {$arg[1]}]";
        }
    }
    
    $content = 'Lorem ipsum {shortcode 42} dolor sit amet.';
    echo preg_replace_callback('/\{shortcode (\d+)\}/i', 'MyClass::myFunction', $content);
    

    Fiddle.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-16
      • 2020-02-21
      • 2020-01-06
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多