Home  >  Article  >  Backend Development  >  How to Write a PHP Regular Expression to Ignore Escaped Quotes Within Quoted Strings?

How to Write a PHP Regular Expression to Ignore Escaped Quotes Within Quoted Strings?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 00:48:12160browse

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:

  • 1*: Matches any character that is not a double quote (") or a backslash ().
  • (?:\.2): Matches escaped characters ( followed by any non-quote, non-backslash character).
  • s: Enables the dot (.) character to match newlines.

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.


  1. "\
  2. "\

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!

Statement:
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