Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing additional arguments to preg_replace_callback using PHP 5.2.6

Tags:

I've been researching similar questions, but I'm still a bit unclear if it's possible and/or best way to pass additional arguments in preg_replace_callback using PHP 5.2.6

In this case I'm also looking to pass the $key from the foreach loop along to the if_replace function.

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]; } 

Wondering if something like this would work:

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); 
like image 886
jsuissa Avatar asked Mar 03 '12 23:03

jsuissa


1 Answers

Before PHP 5.3

You can use helper class:

class MyCallback {     private $key;      function __construct($key) {         $this->key = $key;     }      public function callback($matches) {         return sprintf('%s-%s', reset($matches), $this->key);     } }  $output = 'abca'; $pattern = '/a/'; $key = 'key'; $callback = new MyCallback($key); $output = preg_replace_callback($pattern, array($callback, 'callback'), $output); print $output; //prints: a-keybca-key 

Since PHP 5.3

You can use anonymous function:

$output = 'abca'; $pattern = '/a/'; $key = 'key'; $output = preg_replace_callback($pattern, function ($matches) use($key) {             return sprintf('%s-%s', reset($matches), $key);         }, $output); print $output; //prints: a-keybca-key 
like image 149
Furgas Avatar answered Oct 16 '22 05:10

Furgas