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