Home > Backend Development > PHP Tutorial > How to Ignore Escaped Quotes in PHP Regex?

How to Ignore Escaped Quotes in PHP Regex?

Patricia Arquette
Release: 2024-11-28 17:29:11
Original
467 people have browsed it

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';
Copy after login

Single Quotes:

$re_sq = "/'[^'\\]*(?:\\.[^'\\]*)*'/s";
Copy after login

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 );
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template