1

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

2
  • Remove \g, replace with '$0' . $id Commented Mar 5, 2019 at 19:06
  • I mean my regex is working fine. I need to help with getting matching value in php and add id to it. Commented Mar 5, 2019 at 19:07

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, very much, I will accept as soon as it will be allowed.
@PiotrWadycki Piotrze, I recommend to switch to the string replacement pattern in the JS code since it is said to be most efficient. The arrow function is cool and very powerful indeed, but there is no such necessity here.
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.