RegEx: Find occurrences in code, except when commented

Background

I’ve created a debug helper function in my PHP/WordPress development called TraceIt($value, $type, $param1).
TraceIt does a bit more than just echo out a value. It will format echo out based on value type or specified type, can be environmentally switched to not echo, and can write to a log file.

It’s also easier to find where actual tracing is being used versus the legitimate echo output.

The problem is, sometimes I forget to comment a trace, which is no good, especially when trying to perform a redirect.
And while I usually include a string value in the output that I can search for, sometimes in the heat of the debugging moment I forget that.

 

Solution

The easiest [and some may argue “painful”] way to find occurrences of forgotten TraceIt calls is regex.

What I needed was a way to find all instances of “TraceIt” but not “//TraceIt” (already commented).

And here it is:

^(?!([ \t]*\/\/[ \t]*TraceIt)|[ \t]*\/\/).*((^TraceIt)|( TraceIt)|(\tTraceIt)|(;TraceIt))

You can see it in action, with an explanation of each component, at https://regexr.com/46nbq.

The only problem with this is it also picks up instances of TraceIt on a line that already has //TraceIt earlier in the line.  But I can live with those rare occurences for now.

Oh, and don’t forget to use the /gim flags (global, case insensitive and multi-line).

 

The regex will find occurrences like this:

coding is here; TraceIt("aaaa");
TraceIt("aaaa");
another line of code;
TraceIt('bbb'); more code
TraceIt('ccc');
TraceIt('bbb');
some more code; TraceIt("adsfadfa");

But not like this:

//TraceIt("aaaa");
//TraceIt("bbb"); TraceIt("ccc")
// TraceIt("ddd");
// TraceIt("ddd");
// TraceIt("eee");

another line of code;

some code; //TraceIt('fff');
    //     // TraceIt("gggg");