Home >Backend Development >PHP Tutorial >How Can I Explode a String with Embedded Quotations, Including Escaped and Percent-Encoded Quotes?

How Can I Explode a String with Embedded Quotations, Including Escaped and Percent-Encoded Quotes?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 08:58:10450browse

How Can I Explode a String with Embedded Quotations, Including Escaped and Percent-Encoded Quotes?

Exploding Strings with Embedded Quotations

Exploding a string using the standard explode() function can be problematic when dealing with text within quotation marks. To achieve the desired result of treating quoted words as single entities, a more sophisticated approach is required.

Using Regular Expressions

Regular expressions provide a powerful solution for this task. The following regex matches quoted strings allowing for escaped quotes:

"(?:\.|[^\"])*"|\S+

This pattern can be used with preg_match_all() to extract both quoted and non-quoted words from the string:

$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \"elit" dolor';
preg_match_all('/"(?:\.|[^\"])*"|\S+/', $text, $matches);

The resulting array will contain the desired output:

Array
(
    [0] => Array
        (
            [0] => Lorem
            [1] => ipsum
            [2] => "dolor sit amet"
            [3] => consectetur
            [4] => "adipiscing \"elit"
            [5] => dolor
        )
)

Explanation

The regex pattern consists of two parts:

  • Quoted strings: Enclosed in double quotes, it allows for escaped quotes using \.
  • Non-quoted words: Matches any sequence of non-whitespace characters.

The non-capture group (?:...) ensures that the escaped quotes are not captured as separate matches.

Handling Percent-Encoded Quotes

If your string contains percent-encoded quotes instead of double quotes, modify the regex to:

%22(?:\.|(?!%22).)*%22|\S+

The above is the detailed content of How Can I Explode a String with Embedded Quotations, Including Escaped and Percent-Encoded 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