Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex PHP Only Match if Not Surrounded By Quotes

Tags:

regex

php

I have some regex I run over an entire HTML page looking for strings and replacing them, however if the string is in single or double quotes I do not want it to match.

Current Regex: ([a-zA-Z_][a-zA-Z0-9_]*)

I would like to match steve,john,cathie and john likes to walk (x3) but not "steve", 'sophie' or "john"'likes'"cake"

I have tried (^")([a-zA-Z_][a-zA-Z0-9_]*)(^") but get no matches?

Test Cases:

(steve=="john") would return steve
("test"=="test") would not return anything
(boob==lol==cake) would return all three
like image 947
Pez Cuckow Avatar asked Mar 04 '11 17:03

Pez Cuckow


1 Answers

Try this one:

(\b(?<!['"])[a-zA-Z_][a-zA-Z_0-9]*\b(?!['"]))

Against this string:

john "michael" michael 'michael elt0n_john 'elt0n_j0hn'
 1      2        3        4       5            6

It would match nr 1 john, nr 3 Michael and nr 5 elt0n_john

like image 163
PatrikAkerstrand Avatar answered Oct 03 '22 09:10

PatrikAkerstrand