0

I have a long PHP file and I want to copy all the variable names only and build an insert sql query. Is there a way where I can search for a pattern using regular expression and concatenate the find result till I collected all the variable and spit it out in a statement?

I am using TextMate and am familiar with regular expression search. Regex search result give $0,$1 and so forth argument. Do not know if this possible though. Solution in any editor will do not just text mate.

I have just too many variable (+100) don't feel like copy every single one. Here my sample file

$ID = $_POST['id'];
$TXN_TYPE = $_POST['txn_type'];
$CHARSET = $_POST['charset']
$CUSTOM = $_POST['custom'];
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136

3 Answers3

1

You could try something with get_defined_vars(). However this function also lists GLOBAL vars. You can use this snippet to remove them if you don't want them and display only the vars you defined

$variables = array_diff(get_defined_vars(), array(array()));

However this snippet generates Notices and I haven't found a way to solve them yet.

If you've only got $_POST variables you can loop through the $_POST array itself You create the SQL programmatically while looping through the array.

0

My own solution is, do the inverse. It is not probably possible.

Leave only the variable names Remove all the rest. Use

[space].+  regex to remove everything that is after the variable name.

clean the file so that only variable names are left. then do a couple more find and replace to bring the variable name in the form you want.

TheTechGuy
  • 16,560
  • 16
  • 115
  • 136
0

If you're looking to match only the variable names (not the $_POST array indices), then the regular expression is pretty much provided in the PHP documentation:

\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

This will, of course, include $_POST, but that should be easy enough to remove. If not, you could do it with negative lookahead (if TextMate supports it):

\$(?!_POST($|[^a-zA-Z0-9_\x7f-\xff]))[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Jonathan S.
  • 2,238
  • 16
  • 16
  • It's worth noting that this would return false positives if your PHP file included strings like `$asdf = 'asdfklasdflkj$asdfasdf';`. I'm guessing this isn't the case, but if you want something more powerful, you'd be better off avoiding regular expressions in favor of a solution more like Constantine's. – Jonathan S. May 27 '12 at 20:44
  • Looks good, I will investigate. I already used my own solution though. – TheTechGuy May 27 '12 at 21:11