Home >Backend Development >PHP Tutorial >How to Split a String into Words While Preserving Quoted Phrases?
How to Split Strings by Words, Preserving Quoted Text
For the given string "Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor," we seek a method to explode it into an array, maintaining the integrity of quoted phrases. Using the provided code:
$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor" $noquotes = str_replace("%22", "", $mytext"); $newarray = explode(" ", $noquotes);
results in individual words being split. To address this, we leverage regular expressions:
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \"elit" dolor'; preg_match_all('/"(?:\\.|[^\\"])*"|\S+/', $text, $matches);
This regex matches either quoted strings or non-whitespace characters. Quoted strings can contain escaped double quotes ("), and the technique accommodates that. The result:
Array ( [0] => Array ( [0] => Lorem [1] => ipsum [2] => "dolor sit amet" [3] => consectetur [4] => "adipiscing \"elit" [5] => dolor ) )
Explanation:
The regex can be broken down into its components:
The above is the detailed content of How to Split a String into Words While Preserving Quoted Phrases?. For more information, please follow other related articles on the PHP Chinese website!