Splitting Strings while Preserving Quoted Phrases
The task is to explode a given string into an array of words, with the unique requirement that quoted phrases are treated as single units.
To achieve this, one approach involves utilizing regular expression matching. A suitable pattern to capture both quoted phrases and individual words is:
"(?:\.|[^\"])*"|\S+
This pattern consists of two parts separated by an alternation operator (|):
To use this pattern in PHP, one can employ preg_match_all(...):
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \"elit" dolor'; preg_match_all('/"(?:\.|[^\"])*"|\S+/', $text, $matches);
This will populate the $matches array with an array of all captured matches, where quoted phrases will be isolated as single elements.
For example, with the provided input string:
Lorem ipsum "dolor sit amet" consectetur "adipiscing \"elit" dolor
The output of preg_match_all(...) will be:
Array ( [0] => Array ( [0] => Lorem [1] => ipsum [2] => "dolor sit amet" [3] => consectetur [4] => "adipiscing \"elit" [5] => dolor ) )
The above is the detailed content of How Can I Split a String into Words While Keeping Quoted Phrases Intact?. For more information, please follow other related articles on the PHP Chinese website!