How to Split a String by Multiple Spaces or Tabs in PHP?

Patricia Arquette
Release: 2024-11-22 09:51:12
Original
799 people have browsed it

How to Split a String by Multiple Spaces or Tabs in PHP?

Separating Strings Using Multiple Spaces or Tabs

In programming, it is often necessary to split a string into smaller chunks based on specific criteria. One common use case is to explode a string by one or more spaces or tabs.

Consider the following scenario:

A      B      C      D
Copy after login

We wish to convert this string into an array element by element:

[A, B, C, D]

To achieve this, we can utilize the preg_split() function, which accepts a regular expression pattern as its first parameter and the string to be split as the second parameter. The pattern we need to specify is one that matches one or more consecutive spaces or tabs (s ).

In PHP, the code to perform this operation would be:

$str = "A      B      C      D";
$parts = preg_split('/\s+/', $str);
Copy after login

Now, the $parts array will contain the individual elements of the original string:

print_r($parts);
/*
Output:
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
)
*/
Copy after login

The above is the detailed content of How to Split a String by Multiple Spaces or Tabs in PHP?. 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