Home >Backend Development >PHP Tutorial >How Can I Split a String into Words While Keeping Quoted Phrases Intact?

How Can I Split a String into Words While Keeping Quoted Phrases Intact?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 16:20:09871browse

How Can I Split a String into Words While Keeping Quoted Phrases Intact?

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 (|):

  1. "(?:\.|[^\"])*": This matches a string enclosed in double quotes ("). It also accounts for escaped quotes () within the quoted text using non-capturing group 1.
  2. S : This matches one or more non-whitespace characters, which represents individual words.

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!

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