what I want is a regular expression that matches a php string. So that means everything between " and ", excluding the \". My expression until now has been
/"([^\"]*)"/As
but that one is not correct. For example with this string
"te\"st"
it matches "tes\ whilst it should match "te\"st". I also tried this one:
/"([^\"].*)"/As
which matches the above string correctly, yet when I have this string "te\"st"" it matches "te\"st"", whilst it should only match "te\"st"
Any help appreciated!
Here is the regex you want:
(?<!\\)"(?:\\\\|\\"|[^"\r\n])*+"
I can make you a shorter variation, but it will not be as solid.
See the demo.
Explanation
(?<!\\) asserts that what precedes is not a backslash(?:\\\\|\\"|[^"\r\n]) matches a double backslash, an escaped quote \" or any chars that are not quotes and newline chars (assuming a string on one line; otherwise take out the \r\n)* repeats zero or more times and the + prevents backtracking" matches the closing quoteTo use it:
$regex = '/(?<!\\\\)"(?:\\\\\\\\|\\\\"|[^"\r\n])*+"/';
if (preg_match($regex, $yourstring, $m)) {
$thematch = $m[0];
}
else { // no match...
}
You can use this pattern:
/\A"(?>[^"\\]+|\\.)*"/s
in php code you must write:
$pattern = '/\A"(?>[^"\\\]+|\\\.)*"/s';
pattern details:
\A # anchor for the start of the string
"
(?> # open an atomic group (a group once closed can't give back characters)
[^"\\]+ # all characters except quotes and backslashes one or more times
|
\\. # an escaped character
)*
"
/s singleline mode (the dot can match newlines too)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With