Replace a string that matches a pattern using preg_replace_callback

主宰稳场 提交于 2021-01-27 21:41:59

问题


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.


回答1:


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.


来源:https://stackoverflow.com/questions/64314312/replace-a-string-that-matches-a-pattern-using-preg-replace-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!