Question

I have a preg_replace_callback which takes a closure (anonymous) function as 2nd parameter and it works perfectly fine on local, but when I deploy it to live environment it results in error => Internal server error 500. When i remove the Closure it works.

$regExPattern = '/\<%(?<content>.*?)%\>/';
$template = preg_replace_callback($regExPattern, function ($matches)  use ($dataItem) {
    if(isset($dataItem[trim($matches['content'])])) {
        return $dataItem[trim($matches['content'])];
    }
    else {
        return '';
    }
}, $template);

Any suggestions how can i work arround this problem. I need to use $dataItem inside my callback function and pass it to preg_replace_callback. My development environment is code igniter.

Was it helpful?

Solution

Anonymous functions only work in PHP 5.3 and up. You could use create_function() instead:

$regExPattern = '/\<%(?<content>.*?)%\>/';
$template = preg_replace_callback($regExPattern, create_function(
      '$matches'
    , 'if(isset($dataItem[trim($matches[\'content\'])])) {
          return $dataItem[trim($matches[\'content\'])];
      }
      else {
          return "";
      }'
    )
);

Untested, of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top