generic preg_replace

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
bartfor
Forum Newbie
Posts: 4
Joined: Thu Aug 27, 2009 6:50 am

generic preg_replace

Post by bartfor »

string1:

Code: Select all

employee_id, 13
string2:

Code: Select all

employee_id, 13, status_id, 35
string3:

Code: Select all

employee_id, 13, status_id, 35, menu_id, 4
string4:

Code: Select all

etc..
So its always \w+,[0-9]+

I would like to convert the strings into:

1: employee_id=13
2: employee_id=13 AND status_id=35
3: employee_id=13 AND status_id=35 AND menu_id = 4

with one and the same expression

for string 1 it would be:

Code: Select all

preg_replace('(\w+),([0-9]+)','$1=$2 ' $string);
But I have a hard time making it generic for an x number of parameter additions

Any suggestions?
bartfor
Forum Newbie
Posts: 4
Joined: Thu Aug 27, 2009 6:50 am

Re: generic preg_replace

Post by bartfor »

Found the answer myself.

Code: Select all

preg_replace(array('/([0-9]+),(\w+)/', '/(\w+),([0-9]+)/'),array('$1 AND $2', '$1=$2'),$string);
Post Reply