2

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:

// $string is the string to be searched
$string = preg_replace_callback('/binary_function\(\[(\S),(\S)\]\)/', function ($word) {
        $result = strtoupper($word[1]) . strtoupper($word[2]);              
        return $result;
        }, $string);

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:

// $string is the string to be searched
$string = preg_replace_callback('/binary_function\(\[(\S+),(\S+)\]\)/', function ($word) {
        $result = strtoupper($word[1]) . strtoupper($word[2]);              
        return $result;
        }, $string);

but it did not work.

Can anyone please help here?

Thanks.

2
  • 1
    '/binary_function\(\[([^][\s,]+),([^][\s,]+)]\)/' Commented Oct 12, 2020 at 8:37
  • Awesome :-) Thanks a bunch. Commented Oct 12, 2020 at 8:52

1 Answer 1

0

You can use

'/binary_function\(\[([^][\s,]+),([^][\s,]+)]\)/'

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

1 Comment

Thanks a lot for the detailed explanation.

Your Answer

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