Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match a programming string

Tags:

regex

php

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!

like image 730
user3828747 Avatar asked Dec 05 '25 04:12

user3828747


2 Answers

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

  • The negativelookbehind (?<!\\) asserts that what precedes is not a backslash
  • match the opening quote
  • (?:\\\\|\\"|[^"\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 quote

To use it:

$regex = '/(?<!\\\\)"(?:\\\\\\\\|\\\\"|[^"\r\n])*+"/';
if (preg_match($regex, $yourstring, $m)) {
    $thematch = $m[0];
    } 
else { // no match...
     }
like image 152
zx81 Avatar answered Dec 07 '25 20:12

zx81


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)
like image 27
Casimir et Hippolyte Avatar answered Dec 07 '25 18:12

Casimir et Hippolyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!