vim: Quickly assign POST variables in PHP

David Nash vim Leave a Comment

You’ve got a web form with lots of fields, and you want to POST them to a PHP script. Open vim, and list the INPUT tag’s NAME attributes, one per line.

<?php
firstname
lastname
address1
address2
state
postcode
?>

Now with some search-and-replace magic we can save ourself a lot of boring typing. Hit ‘escape’ to get out of insert mode, type a colon (“:”) and copy-paste this:

%s/^\(\S\+\)/\$\1 = \$_POST\[\'\1\'\];

I won’t bother explaining it unless someone asks. But what you should end up with is this:

<?php
$firstname = $_POST[‘firstname’];
$lastname = $_POST[‘lastname’];
$address1 = $_POST[‘address1’];
$address2 = $_POST[‘address2’];
$state = $_POST[‘state’];
$postcode = $_POST[‘postcode’];
?>

Perhaps not worth it when you have 6 variables like this example; but quite handy when you have 60 variables!

Leave a Reply

Your email address will not be published. Required fields are marked *