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
Release: 2024-12-12 16:20:09
Original
814 people have browsed it

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+
Copy after login

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

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

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

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!

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