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
वर्ग का एक उदाहरण उदाहरण में) कॉलबैक समारोह में previuosly प्रारंभ वस्तु का एक उदाहरण पारित करने के लिए की जरूरत है।
मैं call_user_func()
का उपयोग करने के लिए tryed है, लेकिन काम नहीं करता है (इस तरह से becose मैं matches
पैरामीटर याद आती है)।
वहाँ ऐसा करने के लिए एक रास्ता है, या मैं प्रक्रिया अलग करने के लिए है (preg_match_all
से पहले कर रही है, प्रत्येक मैच के लिए की जगह मान प्राप्त है, और फिर एक सरल preg_replace
)?
संपादित करें: अतिरिक्त नोट के रूप में, टॉम Haigh जवाब से पहले, मैं प्रयोग किया जाता है इस काम के आसपास (उदाहरण में, इस पद्धति की जगह है):
$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;
}
आशा किसी की मदद कर सकते हैं।
यह काम करता है! मैंने सोचा कि कक्षा विधि स्थिर होना चाहिए, याद नहीं है कि मैंने इसे कहाँ पढ़ा ..शायद मैं बिल्कुल भी नहीं था और मैं कुछ वाक्य के साथ गंदा। धन्यवाद – Strae