Badałem podobne pytania, ale wciąż nie jestem pewien czy jest to możliwe i/lub najlepszy sposób przekazania dodatkowych argumentów w preg_replace_callback przy użyciu PHP 5.2.6Przekazywanie dodatkowych argumentów do preg_replace_callback za pomocą PHP 5.2.6
W tym przypadku zamierzam również przekazać klucz $ z pętli foreach do funkcji 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];
}
Zastanawiasz się, czy coś takiego będzie działać:
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);
Funkcja Acallback to zamknięcie, możesz przekazać dodatkowe argumenty za pomocą użycia, sprawdź odpowiedź na http://stackoverflow.com/questions/16445991/how-do-i-access-a-variable-inside-of-preg -replace-callback – Tester