Home >Backend Development >PHP Tutorial >How Can I Extract Quoted Substrings in PHP, Ignoring Escaped Quotes?

How Can I Extract Quoted Substrings in PHP, Ignoring Escaped Quotes?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 12:54:17700browse

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:

  • [^"\\]* matches zero or more non-quote or backslash characters.
  • (?:\\.[^"\\]*)* matches any number of escaped characters followed by non-quote or backslash characters.
  • s modifier enables single-line matching, which is necessary to span multiple lines.

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!

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