PHP Preg Replace 替换数组

发布于 2024-12-22 16:55:35 字数 375 浏览 1 评论 0原文

好吧,我正在尝试这样做:

preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);

现在我知道这是不可能的,但是我想知道是否有办法做到这一点,因为我尝试使用 create_function 但是, $templateVariables 是函数的局部变量,它是内,所以我无法从 create_function 内访问 $templateVariables,所以我有点卡在这里。我宁愿不必找到匹配项找出用什么来替换它们,然后再次找到它们来替换,这看起来效率很低。那么,我是否可以从匿名函数中获取局部变量,或者有人有什么好的建议吗?

谢谢。

Ok so I'm trying to do something like so:

preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);

Now I know that is not possible like it is, however I would like to know if there is a way to do this, because I have tried to use create_function however, $templateVariables is a local variable to the function that it is within, so I can't access $templateVariables from within create_function, so I'm kind of stuck here. I would rather not have to find the matches figure out what to replace them with and then find them again to replace, that just seems horrible inefficient. So is there anyway I can get to a local variable from within an anonymous function or does anyone have any good suggestions.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦归所梦 2024-12-29 16:55:35

试试这个:

$vars = array(
    "test" => "Merry Christmas",
);
$string = "test {test} test";
$string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
    return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
}, $string);
echo $string;

它应该输出:

测试圣诞快乐测试

您可以在此处查看一个工作示例 http://codepad.viper-7.com/2ZNNYZ< /a>

Try this:

$vars = array(
    "test" => "Merry Christmas",
);
$string = "test {test} test";
$string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
    return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
}, $string);
echo $string;

It should output:

test Merry Christmas test

You can see a working example here http://codepad.viper-7.com/2ZNNYZ

森罗 2024-12-29 16:55:35

您实际上可以将 preg_replace 与 /e 修饰符一起使用:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", '$templateVariables[\'$1\']', $templateString)

但这可能不是最安全的方法......

You can actually use preg_replace with /e modifier:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", '$templateVariables[\'$1\']', $templateString)

But it may not be the safest way here...

淡墨 2024-12-29 16:55:35

您需要使用 e 正则表达式修饰符:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", "\$templateVariables['\\1']", $templateString);

You need to use e regexp modifier:

preg_replace("/\{([a-zA-Z0-9_]+)\}/e", "\$templateVariables['\\1']", $templateString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文