piotrruss
piotrruss

Reputation: 439

recreate js regex match function in php

I have a problem with recreation function written in Javascript, to make it work in php. I think that I am really close, but don't understand php syntax that well. So I have something like that in JS:

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

So I try to do the same in php and I have this:

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

So I don't know what to put in "??", because as I understand in JS it is my match arrow function match => match + id, but I can't perform it in PHP. Can anyone help?

Best,

Piotr

Upvotes: 1

Views: 257

Answers (2)

Miroslav Patrashkov
Miroslav Patrashkov

Reputation: 39

You can also use preg_replace_callback(): http://php.net/manual/en/function.preg-replace-callback.php

Thish method will accept a function as its second parameter which is the same as the JS version.

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

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You should not use a global modifier in PHP preg functions, there are specific functions or arguments that control this behavior. E.g. preg_replace replaces all occurrences in the input string by default.

Use

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

Here,

  • ~PR|PD|DD|DPD|DP_AVG~ is a the regex that matches several substring alternatives (note the ~ symbols used as a regex delimiter, in JS, you can only use / for this in the regex literal notation)
  • In the replacement, $0 means the whole match value (same as $& in JS regex), and $id is just appended to that value.

So, in JS version, I'd recommend using

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

Upvotes: 2

Related Questions