Skip to content

Instantly share code, notes, and snippets.

@zanbaldwin
Last active May 24, 2019 00:49
Show Gist options
  • Save zanbaldwin/4b9e4e8eb6d0b96f963ece9d9d909a05 to your computer and use it in GitHub Desktop.
Save zanbaldwin/4b9e4e8eb6d0b96f963ece9d9d909a05 to your computer and use it in GitHub Desktop.
Match strings, allowing for escape characters.

Regular expression to match either a single or double quoted string, taking into account escape characters: /(["'])((?:(?!\1|\\).|\\.)*?)\1/

It's recommended that you remove escape characters from the resulting string (replace \\((?=\%s|\\).) with \1 substituting %s for the matched quote character):

preg_match('/(["\'])((?:(?!\\1|\\\\).|\\\\.)*?)\\1/', $string, $matches);
$extractedStringValue = preg_replace(sprintf('/\\\\((?=\\\\|\\%s).)/', $matches[1]), '\1', $matches[2]);

Examples

String Match? Group 1 Group 2 With Escape Char Removal
'This is a string' Yes ' This is a string This is a string
"This is a string" Yes " This is a string This is a string
"This is a string' No "
"This is a string\" No "
"This is a string\\" Yes " This is a string\\ This is a string\
"This is a string\"" Yes " This is a string\" This is a string"
"This is a string\\\" No "
"This is a string\\\"" Yes " This is a string\\\" This is a string\"
This "is a" string Yes " is a is a
This 'is \a' string Yes ' is \a is \a
This 'is \\a' string Yes ' is \\a is \a
"This \\\"is a\" string" Yes " This \\\"is a\" string This \"is a" string
"This \\\"is a\\" string" Yes " This \\\"is a\\ This \"is a\

Escape Char Removal Examples

Before After
\ \
\\ \
\\" \"
\\\" \"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment