Skip to content
Advertisement

Using preg_replace_callback to find and replace a function signature with a variable number of parameters

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:

JavaScript

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:

JavaScript

See the PHP demo.

You may trim() the input values if there can be spaces inside the ([ and ]).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement