2

I've gotten bitten more than once by a bug where you accidentally assign a variable inside a conditional statement, like if.

I'm looking to grep my sources for such occurances. I created an expression that works in PHP for the simple case, but was wondering if anyone could optimize it or handle the more interesting cases.

Samples:

if ($var = 3)       //MATCH
if($var = 3)        //MATCH
if($var=3)          //MATCH
if ( $var = 3)      //MATCH
if ($var == $var2)  
if ($var = $var3)   //MATCH
if ( $var === 7)
if( $var == 8 || $var = 9) //MATCH
if (($var == 7 ) && ($var ==10))

The simple cases are handled well by if\s*\([\$a-zA-Z\d\s]*=[\$a-zA-Z\d\s]*\) but it would be nice to come up with something that works for the extended versions at the bottom of the sample.

Any ideas on better expressions?

akatakritos
  • 9,836
  • 1
  • 23
  • 29

2 Answers2

4

Regular expressions are not the best tool to parse code.

For most languages there are linting tools that check your code. I have no experience with PHP but you'll find plenty of pointers here: Is there a static code analyzer [like Lint] for PHP files?

Community
  • 1
  • 1
akuhn
  • 27,477
  • 2
  • 76
  • 91
  • Hey thanks for that link, i'll look at some of those tools. I was looking for something quick and dirty, but once one of those tools is up and running, it should give more accurate results. – akatakritos Dec 09 '12 at 23:22
3

First, let's assume you don't have cases like this (C example):

if ((a = b) == c)

because understanding these cases needs an actual parser.

Now, simply put, you want to match = but not ==\+. Therefore:

if\([^=]\|==\+\)*[^=]=[^=]\([^=]\|==\+\)*$

What it says:

  • if: match the first if.
  • [^=]: any character but =
  • ==\+: == and ===
  • \([^=]\|==\+\)*: anything that is not = or is == or ===. This includes all the whitespace, the beginning (, ending ) etc. This comes both before and after the isolated =.
  • [^=]=[^=]: isolated =.
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Awesome. I tried it on my project and it didnt find anything. So I guess that means I wrote good code this time. Ha! Cheers! – akatakritos Dec 09 '12 at 23:23
  • @akatakritos, I'm not a php developer, but I would have expected whatever compiler/interpreter reads that code should give you warnings, doesn't it? – Shahbaz Dec 09 '12 at 23:32
  • Accidental assignment, AFAIK is not any sort of warning in PHP. I miss C# where its a compile error. :( – akatakritos Dec 10 '12 at 00:20