Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP regex selecting a tag while excluding another with an escape character

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading