[VIM] Global Search And Replace

VIM is a very powerful text editor, and it can be quite addictive too ;) Sometime I have a text file which contains a long listing of IDs. I need to create SQL statments to manipulate records with these IDs. Since I am doing my development on Red Hat server, I will use VIM for this task. VIM’s search & replace command is in this format:
:s/pattern/string/flags

Without the flag, only the first matched term, on each line, will be replaced. A g flag can be used to replace all matched term on each line. E.g.:
:s/hello/goodbye/g

This command will only works on 1 line at a time. & can be used on each line to repeat the last :s command. To perform global replacement on the whole file, you can add a % in front of s. The following command will change all  “microsoft” to “microsoap”:
:%s/microsoft/microsoap/g

Back to my MySQL problem. I have a file, which contains a record ID on each line. The following command will create UPDATE statements from the record IDs:
:%s/\(\d\+\)/UPDATE members SET last_login='1970-01-01 00:00:00' WHERE id=\1;

Now I can feed this file into MySQL, and it will reset the members’ last_login date.

Reference:

Posted in Tao Of Programming at June 4th, 2009. No Comments.

[PHP] Camel Case to Underscore

strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $str))

This piece of code turns a camel case string into a lowercase underscore version. (e.g.  'blackTableID' becomes 'black_table_id'). The regrex looks for capitalized letter (prefixed by a lowercase letter), add a underscore between these 2 letters. Finally, the strtolower function convert the resultant string to lowercase.

NOTE: If there are 2 consecutive capitalized letters, no underscore will be added.

Posted in Tao Of Programming at March 27th, 2009. 3 Comments.