Home > Backend Development > PHP Tutorial > How to Split a String into Words While Preserving Quoted Phrases?

How to Split a String into Words While Preserving Quoted Phrases?

Susan Sarandon
Release: 2024-12-06 02:59:17
Original
979 people have browsed it

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);
Copy after login

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);
Copy after login

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
        )

)
Copy after login

Explanation:

The regex can be broken down into its components:

  • `" # Matches the double quote character ("
  • (?: # Start non-capturing group 1
  • # Matches the backslash character ()
  • . # Matches any character except line breaks
  • | # OR
  • 1 # Matches any character except and "
  • )* # End non-capturing group 1 and repeat it zero or more times
  • " # Matches the double quote character ("
  • | # OR
  • S # Matches one or more non-whitespace characters

  1. "

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template