在 php 中重新创建 js 正则表达式匹配函数

recreate js regex match function in php

我在 Javascript 中编写的娱乐函数有问题,要让它在 php 中工作。我认为我真的很接近,但不太了解 php 语法。 所以我在 JS 中有类似的东西:

function convertStr(str, id) {
  const regexExpression = new RegExp('PR|PD|DD|DPD|DP_AVG', 'g');
  return str.replace(regexExpression, match => match + id);
}

所以我尝试在 php 中做同样的事情,我有这个:

$reg = "/PR|PD|DD|DPD|DP_AVG\g/";
$result = preg_replace($reg, ??, $str)

所以我不知道在“??”中放什么,因为我在 JS 中理解它是我的匹配箭头函数 match => match + id,但我无法在 [=27= 中执行它]. 有人可以帮忙吗?

最佳,

彼得

您不应在 PHP preg 函数中使用全局修饰符,有特定的函数或参数可以控制此行为。例如。 preg_replace 默认替换输入字符串中的所有匹配项。

使用

function convertStr($str, $id) {
  $regexExpression = '~PR|PD|DD|DPD|DP_AVG~';
  return preg_replace($regexExpression, '[=10=]' . $id, $str);
}

这里,

  • ~PR|PD|DD|DPD|DP_AVG~ 是一个匹配多个子字符串的正则表达式(注意 ~ 符号用作正则表达式分隔符,在 JS 中,您只能在正则表达式文字符号)
  • 在替换中,[=16=] 表示整个匹配值(与 JS 正则表达式中的 $& 相同),$id 只是附加到该值。

所以,在 JS 版本中,我建议使用

return str.replace(regexExpression, "$&" + id);

您也可以使用preg_replace_callback()http://php.net/manual/en/function.preg-replace-callback.php

Thish 方法将接受一个函数作为它的第二个参数,这与 JS 版本相同。

$str = "...";
$id = 0;
preg_replace_callback("Your regex expression", function($match) {
    return $match[0] + $id;
}, $str);