I feel like I should be able to find the answer to this but I can’t seem to figure it out. I have a basic string of characters in a php file which I’m searching with regex. The search works great but I can’t figure out how to exclude certain tags based on escape characters.
This is my search string
@section('content')
\@section('test')
\@endsection
@endsection
I’m trying to select @section("X") unless it’s escaped with "\" first. So the second occurence where it says "\@section(‘test’)" wouldn’t match because of the escape char.
Here’s my regex which does work to select all occurences.
preg_match("/\@section\(\'\S*\'\)/i", $file_data, $start_section_match);
I thought I was on the right track with use of the "^" symbol but I’m not really sure. I know it could be done with a little php work but I’m just curious if there’s a way to do it with just regex. Thanks!
>Solution :
This should do it for you…
preg_match("/(?<!\\)\@section\(\'\S*\'\)/i", $file_data, $start_section_match);
That’s a negative lookbehind saying if the previous character is not a backslash. It doesn’t actually match anything, it just checks for that.