Using the PHP preg_replace_callback function, I want to replace the occurrences of the pattern “function([x1,x2])” with substring “X1X2”, “function([x1,x2,x3])” with substring “X1X2X3”, and in general: “function([x1,x2,…,x2])” with substring “X1X2…Xn” — in a given string.
Thanks to Wiktor in this previous question, I have it working for functions that take two arguments:
// $string is the string to be searched $string = preg_replace_callback('/function([([^][s,]+),([^][s,]+)])/', function ($word) { $result = strtoupper($word[2]) . strtoupper($word[2]); return $result; }, $string);
I want to move one step further and make it work for functions with an arbitrary number of arguments. I tried using the regex '/function([[([^][s,]+)]+[,]*])/'
as a way of saying I want a repeated non-white substring followed optionally by a comma — to account for the last function argument that is not followed by a comma. This however made PHP moan about the regex not being correct.
Any help is appreciated,
Thanks.
Advertisement
Answer
You can match and capture all contents between function([
and ])
with a simple binary_function([(.*?)])
regex and then split the contents with a comma, and join back the uppercased strings:
$text = 'binary_function([x,y]) and binary_function([x1,y1,z1])'; echo preg_replace_callback('~binary_function([(.*?)])~', function ($m) { return implode("", array_map(function ($x) { return strtoupper($x); }, explode(",", $m[1]))); }, $text); // => XY and X1Y1Z1
See the PHP demo.
You may trim()
the input values if there can be spaces inside the ([
and ])
.