Skip to content
Advertisement

Replace a string that matches a pattern using preg_replace_callback

I want to replace the occurrences of the pattern “binary_function([x,y])” with substring “XY” in a given string.

I have it working with the following code:

JavaScript

However, I also want it to replace “binary_function([x1,y1])” with substring “X1Y1”, and any length of the arguments inside the square brackets e.g. [x11,y12], [var1,var2], etc.

I tried this:

JavaScript

but it did not work.

Can anyone please help here?

Thanks.

Advertisement

Answer

You can use

JavaScript

See the regex demo

Regex details

  • binary_function([ – a binary_function([ text
  • ([^][s,]+) – Group 1: any one or more (due to +) chars other than ], [, whitespace and ,
  • , – a comma
  • ([^][s,]+) – Group 2: any one or more (due to +) chars other than ], [, whitespace and ,
  • ]) – a ]) string.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement