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