我有一个非常古老的遗留项目我需要开始使用php 5.6: - (
我需要用preg_replace替换e修饰符的使用并使用preg_repolace_callback instaead。
我的替换标记为原始代码:
//REPLACED THIS $in= '!\[\~([0-9]+)\~\]!ise';
//WITH THIS
$in= '!\[\~([0-9]+)\~\]!is'
$isfriendly= ($this->config['friendly_alias_urls'] == 1 ? 1 : 0);
$pref= $this->config['friendly_url_prefix'];
$suff= $this->config['friendly_url_suffix'];
$thealias= '$aliases[\\1]';
$found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff',$thealias)";
$not_found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff','" . '\\1' . "')";
$out= "({$isfriendly} && isset({$thealias}) ? {$found_friendlyurl} : {$not_found_friendlyurl})";
//I NEED TO REPLACE THIS $documentSource= preg_replace($in,$out, $documentSource);
//WITH WHAT?
我试过
$documentSource= preg_replace_callback($in,create_function('$isfriendly,$thealias,$found_friendlyurl,$not_found_friendlyurl',"({$isfriendly} && isset({$thealias}) ? {$found_friendlyurl} : {$not_found_friendlyurl})"), $documentSource);
但是这没有用,给出了无效的回调错误。
有人帮忙吗?我看了SO中的其他例子但由于使用复杂的大括号和对所涉及的函数的一般不熟悉而无法解决这个问题。
感谢。
答案 0 :(得分:1)
看到你主要使用属性($this->…
),最好不要将自定义回调定义为匿名函数,而是将方法定义为:
public function preg_callback($matches) {
#-- Retain the flag lookups:
$isfriendly = ($this->config['friendly_alias_urls'] == 1 ? 1 : 0);
$pref = $this->config['friendly_url_prefix'];
$suff = $this->config['friendly_url_suffix'];
#-- Exchange `\\1` placeholder for $matches[1]
$thealias = $aliases[$matches[1]];
# ↑ needs to become an property
#-- Rearrange the odd expression salad into a proper condition:
if ($isfriendly && isset($thealias)) {
# ↑ likely needs a lookup elsewhere
# formerly `$found_friendlyurl`
return $this->makeFriendlyURL($pref, $suff, $thealias);
}
else {
# or `$not_found_friendlyurl`
return $this->makeFriendlyURL($pref, $suff, $matches[1]);
} # ↑ `\\1`
}
请注意,这是只是一个松散的语法示例。 (我不会完全重写你的代码。)
$aliases
变成属性。preg_replace_callback($rx, [$this, "preg_callback"], $src);
这里重要的一点是,您只需撤消所有繁琐的变量插值和双重转义,这对于内联/eval
- 模式是必要的。