【发布时间】:2012-04-12 20:30:40
【问题描述】:
这段代码:
$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
create_function(
'$matches',
'return $matches[1] + $t;'
), $func);
如何使 $t 在 preg_replace() 函数中的 create_function() 中可见?
【问题讨论】:
-
你应该使用闭包代替php.net/functions.anonymous
function($matchtes)use($t){/*..*/} -
@hakre
"1" + 100;) 但是我明白了,您的意思是:正则表达式匹配以Name开头的内容,因此该函数将始终返回100(=$t)。可能不想要。 -
解决方案取决于您使用的 PHP 版本。理想情况下,解决方案是使用将 $t 变量传递给
use构造的闭包。这至少需要 PHP 5.3。顺便说一句,如果 $t 的值不是每次都发生变化,您可以考虑使用在任何上下文中都可用的常量。
标签: php preg-replace global-variables preg-replace-callback create-function