开发者

How to pass parameter with preg_replace() with 'e' modifier?

开发者 https://www.devze.com 2022-12-15 11:36 出处:网络
I have a question about preg_replace() function. I\'m using it with \'e\' modifier. Here is code snippet:

I have a question about preg_replace() function. I'm using it with 'e' modifier. Here is code snippet:

$batchId = 2345;
$code = preg_replace("/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/e",
                     'translate_indicator(\'$0\', {$batchId})', $code);

I want to have access to $batchId variable inside translate_indicator($code, $batch=false) function. The above exapmle, unfortunately, doesn't work correctly: $batch is invisible(var_dump() result is bool(false)) within translate_indicator().

Probably, I have syntax mistakes in replacement code. Or, maybe, it's impossible to pass variables with preg_replace()?

Update for the first two answers.

Thank you for answers, but your advice didn't help. Besides I've already tried double qoutes instead of single qoutes. I've just simplified code to test possibility of passing parameter to the function:

$code = preg_replace("/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/e",
                     "translate_indicator('$0', 12)", $code);

Also I've removed default value for the $batch within translate_indicator(). Result:

Warning: Missing argument 2 for translate_indicator()

So I think it's impossible to p开发者_如何学Pythonass parameter using this approach.:(


$batchId = 2345;
$code = 'AA1#';
$code = preg_replace(
  "/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/e",
  "translate_indicator('\$0', $batchId)", /* if $batchId can be a string use 'batchId' */
  $code);

function translate_indicator($s, $batchId) {
  echo "translate_indicator($s, $batchId) invoked\n";
}

prints translate_indicator(AA1#, 2345) invoked.
You can also use preg_replace_callback and a class/an object

class Foo {
  public $batchId = 2345;
  public function translate_indicator($m) {
    echo "batchId=$this->batchId . $m[0]\n";
  }
}

$code = 'AA1#';
$foo = new Foo;
$code = preg_replace_callback(
  '/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/',
  array($foo, 'translate_indicator'),
  $code
);

As of php 5.3. you can also use an anonymous function + closure to "pass" the additional parameter.

$code = 'AA1#';
$batchId = 2345;
$code = preg_replace_callback(
  '/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/',
  function($m) use ($batchId) {
    echo "batchid=$batchId . code=$m[0]\n";
  },
  $code
);


try this instead

$batchId = 2345;
$code = preg_replace("/[A-Za-z]{2,4}[\d\_]{1,5}[\.YRCc]{0,4}[\#\&\@\^]{0,2}/e",
                     "translate_indicator('$0', {$batchId})", $code);

singly-quoted strings aren't expanded (i.e. $batchId won't be subsituted).


Use "translate_indicator('\$0', $batchId)" instead of 'translate_indicator(\'$0\', {$batchId})'.

0

精彩评论

暂无评论...
验证码 换一张
取 消