php - 使用 PHP 5.2.6 将附加参数传递给 preg_replace_callback

标签 php

我一直在研究类似的问题,但我仍然不太清楚使用 PHP 5.2.6 在 preg_replace_callback 中传递附加参数是否可能和/或最好的方法

在这种情况下,我还希望将 $key 从 foreach 循环传递到 if_replace 函数。

public function output() {
if (!file_exists($this->file)) {
    return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);

foreach ($this->values as $key => $value) {
    $tagToReplace = "[@$key]";
    $output = str_replace($tagToReplace, $value, $output);
    $dynamic = preg_quote($key);
    $pattern = '%\[if @'.$dynamic.'\](.*?)\[/if\]%'; // produces: %\[if @username\](.*?)\[/if\]%
    $output = preg_replace_callback($pattern, array($this, 'if_replace'), $output);
}

return $output;
}



public function if_replace($matches) {

    $matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
    $matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
    return $matches[0];
}

想知道这样的事情是否可行:

class Caller {

public function if_replace($matches) {

    $matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
    $matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
    return $matches[0];
}

}

$instance = new Caller;

$output = preg_replace_callback($pattern, array($instance, 'if_replace'), $output);

最佳答案

PHP 5.3 之前

你可以使用辅助类:

class MyCallback {
    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    public function callback($matches) {
        return sprintf('%s-%s', reset($matches), $this->key);
    }
}

$output = 'abca';
$pattern = '/a/';
$key = 'key';
$callback = new MyCallback($key);
$output = preg_replace_callback($pattern, array($callback, 'callback'), $output);
print $output; //prints: a-keybca-key

自 PHP 5.3 起

你可以使用匿名函数:

$output = 'abca';
$pattern = '/a/';
$key = 'key';
$output = preg_replace_callback($pattern, function ($matches) use($key) {
            return sprintf('%s-%s', reset($matches), $key);
        }, $output);
print $output; //prints: a-keybca-key

关于php - 使用 PHP 5.2.6 将附加参数传递给 preg_replace_callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550769/

相关文章:

php - 在页面加载时运行 javascript

ubuntu - phpinfo() 什么也没显示,但我所有其他 php 脚本都可以正常工作

php - 将xml数据存入mysql数据库

php - 如何在 Laravel 中过滤缓存的查询

php - 使用 SQL windows 函数编写查询来计算一个国家/地区城市人口的运行总数

php - 检查产品是否可以在 WooCommerce 中下载

php - 使用 iframe 将第三方 cookie 设置到 safari。不支持 P3p header

PHP/MySQL : How to distinct duplicated id from nested loop

javascript - 在回显时连接 PHP 和 JS

php - 输入字段中的多维数组