Home >Backend Development >PHP Tutorial >How Can I Extract Quoted Substrings in PHP, Ignoring Escaped Quotes?
Excluding Escaped Quotes in PHP Regex
In PHP, extracting substrings enclosed by single or double quotes requires careful attention to escape sequences. To ignore escaped quotes within the matched string, we can utilize advanced regular expressions.
Consider the following code:
$code = preg_replace_callback('/"(.*?)"/', array(&$this, '_getPHPString'), $code); $code = preg_replace_callback("#'(.*?)'#", array(&$this, '_getPHPString'), $code);
These regexes match substrings between quotes, but they fail to exclude escaped quotes. To address this issue, we employ more comprehensive regex patterns:
Recommended Regexes:
Double-Quoted Substrings:
"[^"\\]*(?:\\.[^"\\]*)*"/s
Single-Quoted Substrings:
/'[^'\\]*(?:\\.[^'\\]*)*'/s
These regexes allow for any non-escaped character, including escaped characters (e.g., "n" and "t"), and escaped-escape sequences ("").
Explanation:
By incorporating these regexes, you can accurately extract substrings that include escaped characters within quoted strings.
The above is the detailed content of How Can I Extract Quoted Substrings in PHP, Ignoring Escaped Quotes?. For more information, please follow other related articles on the PHP Chinese website!