Reg exp to edit a query

I have a list of dynamically generated queries, for example:

INSERT INTO table1 SET firstname = “Patty”, lastname = “Hewes”, id = $last_inserted_id
INSERT INTO table1 SET phone = “5554441122” where id = $last_inserted_id
INSERT INTO table1 SET address = “1200 Freedom Avenue” where id = $last_inserted_id

There is always different table names, but I need to be able to extract the table name from the query. I need a regular expression that will take anything between INSERT INTO and SET.

I will have an array with the queries. Use a foreach loop to analyze query by query. and if there is a repeated table name, then change the query from an INSERT query to an UPDATE query. Will end up with this:

INSERT INTO table1 SET firstname = “Patty”, lastname = “Hewes”, id = $last_inserted_id
UPDATE table1 SET table1 SET phone = “5554441122” where id = $last_inserted_id
UPDATE table1 SET address = “1200 Freedom Avenue” where id = $last_inserted_id

Thanks in advance,

Leo :hr: