【发布时间】:2011-02-10 11:30:16
【问题描述】:
嗯,伙计们,我真的希望我的英语足够好来解释我需要什么。
让我们来看看这个例子(这只是一个例子!)的代码:
class Something(){
public function Lower($string){
return strtolower($string);
}
}
class Foo{
public $something;
public $reg;
public $string;
public function __construct($reg, $string, $something){
$this->something = $something;
$this->reg = $reg;
$this->string = $string;
}
public function Replace(){
return preg_replace_callback($this->reg, 'Foo::Bar', $this->string);
}
public static function Bar($matches){
/*
* [...]
* do something with $matches and create the $output variable
* [...]
*/
/*
* I know is really useless in this example, but i need to have an istance to an object here
* (in this example, the Something object, but can be something else!)
*/
return $this->something->Lower($output);
}
}
$s = new Something();
$foo = new Foo($myregexp, $mystring, $s);
$content = $foo->Replace();
所以,php手册说要在preg_replace_callback()中使用类方法作为回调,方法必须是抽象的。
我需要在回调函数中传递一个先前初始化的对象的实例(在示例中,Something 类的实例)。
我尝试使用call_user_func(),但不起作用(因为这样我错过了matches 参数)。
有没有办法做到这一点,或者让 i 分离进程(在preg_match_all 之前执行,为每个匹配项检索替换值,然后是一个简单的preg_replace)?
编辑: 作为旁注,在汤姆·海格回答之前,我使用了这个解决方法(在示例中,这是替换方法):
$has_dynamic = preg_match_all($this->reg, $this->string, $dynamic);
if($has_dynamic){
/*
* The 'usefull' subset of my regexp is the third, so $dynamic[2]
*/
foreach($dynamic[2] AS $key => $value){
$dynamic['replaces'][$key] = $this->Bar($value);
}
/*
* ..but i need to replace the complete subset, so $dynamic[0]
*/
return str_replace($dynamic[0], $dynamic['replaces'], $this->string);
}else{
return $this->string;
}
希望可以帮助别人。
【问题讨论】:
标签: php preg-replace preg-match preg-match-all preg-replace-callback