का उपयोग कर preg_replace_callback के लिए अतिरिक्त तर्क पास करना मैं इसी तरह के प्रश्नों का शोध कर रहा हूं, लेकिन मैं अभी भी थोड़ा अस्पष्ट हूं यदि यह संभव है और/या PHP 5.2.6PHP 5.2.6
का उपयोग कर preg_replace_callback में अतिरिक्त तर्क पारित करने का सबसे अच्छा तरीका हैइस मामले में मैं if_replace फ़ंक्शन के साथ फ़ोरैच लूप से $ कुंजी पास करने की भी तलाश कर रहा हूं।
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
$dynamic = preg_quote($key);
$pattern = '%\[if @'.$dynamic.'\](.*?)\[/if\]%'; // produces: %\[if @username\](.*?)\[/if\]%
$output = preg_replace_callback($pattern, array($this, 'if_replace'), $output);
}
return $output;
}
public function if_replace($matches) {
$matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
$matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
return $matches[0];
}
अगर कुछ इस तरह काम करेगा सोच:
class Caller {
public function if_replace($matches) {
$matches[0] = preg_replace("%\[if @username\]%", "", $matches[0]);
$matches[0] = preg_replace("%\[/if]%", "", $matches[0]);
return $matches[0];
}
}
$instance = new Caller;
$output = preg_replace_callback($pattern, array($instance, 'if_replace'), $output);
Acallback फ़ंक्शन एक बंद है, आप उपयोग के माध्यम से अतिरिक्त तर्क पारित कर सकते हैं, कृपया http://stackoverflow.com/questions/16445991/how-do-i-access-a-variable-inside-of-preg पर उत्तर की जांच करें -replace-callback – Tester