Home >Backend Development >PHP Tutorial >How to Ignore Escaped Quotes in PHP Regex?
Regex to Ignore Escaped Quotes Within Quotes in PHP
In PHP, it is often necessary to parse and manipulate strings that contain escaped quotes. The existing regular expressions used to match strings within single and double quotes may not ignore escaped quotes, which can lead to unexpected results.
Solution:
To ignore escaped quotes within quotes, we can utilize the following regular expressions:
Double Quotes:
$re_dq = '/"[^"\\]*(?:\\.[^"\\]*)*"/s';
Single Quotes:
$re_sq = "/'[^'\\]*(?:\\.[^'\\]*)*'/s";
These regexes follow the principles outlined by Jeffrey Friedl in his book "Mastering Regular Expressions". They allow for the matching of escaped characters, including quotes.
The recommended PHP code to replace single and double quotes is:
$code = preg_replace_callback( $re_dq, array( &$this, '_getPHPString' ), $code ); $code = preg_replace_callback( $re_sq, array( &$this, '_getPHPString' ), $code );
The above is the detailed content of How to Ignore Escaped Quotes in PHP Regex?. For more information, please follow other related articles on the PHP Chinese website!