In this tutorial, you shall learn how to split a string with one or more adjacent whitespace character(s) as delimiter in PHP using preg_split() function, with the help of example programs.

PHP – Split String by one or more Whitespace Characters

To split a string into parts by one or more whitespace characters (like single space, tab, new line, etc.) as delimiter or separator in PHP, use preg_split() function.

Call preg_split() function and pass the regular expression to match one or more whitespace characters, and the original string as arguments. The function returns an array of strings obtained after splitting the given string.

Syntax

The syntax of preg_split() function to split the $input string by one or more whitespace characters is

preg_split('/\s+/', $input)
ADVERTISEMENT

Example

In this example, we take an input string "apple banana \tcherry\n\t\tmango" where the values are separated by more than one single space, tab space, and new line. We split this string into an array of values.

PHP Program

<?php
$input = "apple    banana \tcherry\n\t\tmango";
$output = preg_split('/\s+/', $input);
foreach ($output as $x) {
    echo $x;
    echo '<br>';
}
?>

Output

PHP - Split String by one or more Whitespace Characters

Conclusion

In this PHP Tutorial, we learned how to split a string by one or more whitespace characters as delimiter/separator, using preg_split() function.