preg_split()
preg_split() splits a string by a regex pattern. More powerful than explode() for variable or multiple delimiters.
preg_split() splits a string by a regex pattern. More powerful than explode() for variable or multiple delimiters.
<?php
// Split on any whitespace
$words = preg_split("/\s+/", " hello world foo ");
// ["", "hello", "world", "foo", ""]
// Remove empty elements
$words = preg_split("/\s+/", trim($text));
// Split on multiple delimiters
$parts = preg_split("/[,;|]/", "a,b;c|d");
// ["a", "b", "c", "d"]
// Keep the delimiter in results (PREG_SPLIT_DELIM_CAPTURE)
$tokens = preg_split("/(\s+)/", "hello world", -1, PREG_SPLIT_DELIM_CAPTURE);
// ["hello", " ", "world"]
Use PREG_SPLIT_NO_EMPTY flag to automatically remove empty strings from the result array.