mmmh家伙,我真的很希望我的英语能够很好地解释我需要什么。有没有办法在preg_replace_callback回调函数中传递另一个参数?
让我们借此例如(这只是一个例子!)的代码:
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
参数)。
有没有办法做到这一点,还是让我分开这个过程(在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;
}
希望可以帮助别人。
This Works!我认为类方法必须是静态的,不要记得我读过它的地方。也许我根本没有做任何事情,而且我对一些句子感到混乱。 谢谢 – Strae 2010-04-21 08:18:45