Friday, August 05, 2005

Find Replace Regular Expressions

I love EditPlus. It's really powerful program.
I was working on some PHP code. I had a list of variables-- column names from a SQL database.
Before:
first_name
initial
last_name
address_1
address_2
city
state
postacode
country_select
organisation
work_phone
fax
home_phone
mobile_phone
I needed to turn the columns into lines in the code that were variables, wrap them with some code and go from there.

After:
$first_name = stripslashes($first_name);
$initial = stripslashes($initial);
$last_name = stripslashes($last_name);
$address_1 = stripslashes($address_1);
$address_2 = stripslashes($address_2);
$city = stripslashes($city);
$state = stripslashes($state);
$postacode = stripslashes($postacode);
$country_select = stripslashes($country_select);
$organisation = stripslashes($organisation);
$work_phone = stripslashes($work_phone);
$fax = stripslashes($fax);
$home_phone = stripslashes($home_phone);
$mobile_phone = stripslashes($mobile_phone);
How? Using Editplus' find-replace regular expression:

Find : ^([^\n]+)
Replace: $\1 = stripslashes($\1);

Translation:
Find: From the beginning of a line (^) look for everything that isn't a line break (a \n or in this case look for a NOT newline (^\n)). Save what you find.
Replace: Take the first thing saved (\1) and use it as the start, put in some PHP code. Use it again. Close off the statement.

Voila.

tags: editplus find-replace regex

No comments: