2

erm...i have a class, trying to make a template class, using preg_replace_callback, but i don't know how the parameter 2 write

class template {
   public function parse_template($newtpl, $cachetpl){
      ......
      $template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
      $template = preg_replace_callback("/\{lang\s+(.+?)\}/is", $this->languagevar('\\1'), $template);
      ......
   }

   public function languagevar($param1){
      ......
      return $lang[$param1];
      ......
   }
}

how this work?

at my html(template) file, have something like this {lang hello}, and the parse_template found the {lang anything} it will convert using $this->languagevar('hello');

but i keep getting error at the

$template = preg_replace_callback("/\{lang\s+(.+?)\}/is", $this->languagevar('\\1'), $template);

the error message was

preg_replace_callback(): Requires argument 2, '('\1')', to be a valid callback

before i can do the callback using

preg_replace("/\{lang\s+(.+?)\}/ies", "\$this->languagevar('\\1')", $template);

but maybe current php version problem, it got error say that /e is deprecated, use preg_replace_callback instead

user259752
  • 1,065
  • 2
  • 9
  • 24

2 Answers2

4

Use:

$template = preg_replace_callback("/\{lang\s+(.+?)\}/is", array($this, 'languagevar'), $template);

And the parameter passed to the callback function is an array of matched elements, so you have to change languagevar to below:

   public function languagevar($matches){
      /// ......
      return $lang[$matches[1]];
   }
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • erm...yesterday i tried this it work, but actually i got a lot of class method using the preg_replace('pattern/ies', '$this->callingmethod('\\1')', $template) to call the same way before, the only way i can do is all the method parameter1 set it $parameter[1] ? any better way to avoid editing all method once again?except downgrade the php version? – user259752 Mar 07 '14 at 06:12
1

You need to provide a valid callback as the second argument to preg_replace_callback. In your case that would be array($this, 'languagevar').

Also note that you can't explicitly pass a captured group to the callback method like you're trying to do. The method will receive an array of all matched elements.

lafor
  • 12,472
  • 4
  • 32
  • 35
  • how do i parse the parameter into languagevar('parameter'), the parameter get from preg_replace (.+?) – user259752 Mar 06 '14 at 15:07
  • @user3040842 Read the manual on `preg_replace_callback`. You can't pick what argument your callback will receive; it will be passed an array of *all elements matching the pattern*. – lafor Mar 06 '14 at 15:15