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

PHP – Split String by any Whitespace Character

To split a string into parts by any whitespace character (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 any whitespace character, and the original string as arguments. The function returns an array of strings obtained after splitting the given string by any whitespace character as separator string.

Syntax

The syntax of preg_split() function to split the $input string by any whitespace character is

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

Example

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

PHP Program

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

Output

PHP - Split String by any Whitespace Character

Conclusion

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