Home > Article > Backend Development > How to Write a PHP Regular Expression to Ignore Escaped Quotes Within Quoted Strings?
PHP: Regular Expression to Ignore Escaped Quotes within Quotes
In this scenario, you aim to modify existing regular expressions that extract strings enclosed by single (') or double (") quotes to ignore escaped quotes within those quotes. The goal is to allow data between single quotes to disregard escaped single quotes (') and data between double quotes to disregard escaped double quotes (").
Solution:
To achieve this, you can utilize the following regular expressions, optimized for efficiency:
Double-Quoted Strings:
"[^"\\]*(?:\\.[^"\\]*)*"/s
Single-Quoted Strings:
/'[^'\\]*(?:\\.[^'\\]*)*'/s
Explanation:
These regular expressions consist of the following components:
By combining these patterns, the regexes effectively capture quoted strings while ignoring escaped quotes.
Example PHP Code:
$re_dq = '/"[^"\\]*(?:\\.[^"\\]*)*"/s'; $re_sq = "/'[^'\\]*(?:\\.[^'\\]*)*'/s"; $code = preg_replace_callback($re_dq, array($this, '_getPHPString'), $code); $code = preg_replace_callback($re_sq, array($this, '_getPHPString'), $code);
This code will now correctly extract quoted strings, ignoring escaped quotes within them.
The above is the detailed content of How to Write a PHP Regular Expression to Ignore Escaped Quotes Within Quoted Strings?. For more information, please follow other related articles on the PHP Chinese website!