Tôi đã nghiên cứu các câu hỏi tương tự, nhưng tôi vẫn chưa rõ ràng nếu có thể và/hoặc cách tốt nhất để chuyển các đối số bổ sung trong preg_replace_callback bằng PHP 5.2.6Gửi các đối số bổ sung cho preg_replace_callback bằng PHP 5.2.6
Trong trường hợp này, tôi cũng đang tìm cách chuyển khóa $ từ vòng lặp foreach cùng với hàm 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];
}
Tự hỏi nếu một cái gì đó như thế này sẽ làm việc:
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);
Chức năng Acallback bị đóng, bạn có thể chuyển thêm đối số thông qua sử dụng, vui lòng kiểm tra câu trả lời tại http://stackoverflow.com/questions/16445991/how-do-i-access-a-variable-inside-of-preg -replace-callback – Tester