Skip to content

Instantly share code, notes, and snippets.

@leandromoh
Created May 15, 2016 17:42
Show Gist options
  • Save leandromoh/fed5d1496e3034a4a9242abd676feeb7 to your computer and use it in GitHub Desktop.
Save leandromoh/fed5d1496e3034a4a9242abd676feeb7 to your computer and use it in GitHub Desktop.
lookahead positive
/foo(?=bar)/ match foo in Hello foobar
lookahead negative
/foo(?!bar)/ matches 'foo', only if it is NOT followed by 'bar'
Lookbehind positive
/(?<=foo)bar/ matches 'bar' only if it is preceded by 'foo'
Lookbehind negative
/(?<!foo)bar/ matches 'bar' if it is NOT preceded by 'foo'
Collectively, lookbehinds and lookaheads are known as lookarounds.
------------------------------
Regular expressions provide the functionality for checking certain conditions.
(?(condition)true-pattern | false-pattern)
or
(?(condition)true-pattern)
The condition can be a number. In which case it refers to a previously captured subpattern.
$pattern = '/^(<)?[a-z]+(?(1)>)$/';
preg_match($pattern, '<test>'); // true
preg_match($pattern, '<foo'); // false
preg_match($pattern, 'bar>'); // false
preg_match($pattern, 'hello'); // true
------------------------------
http://www.rexegg.com/regex-disambiguation.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment