SyntaxStudy
Sign Up
PHP preg_split() for Complex Splitting
PHP Intermediate 4 min read

preg_split() for Complex Splitting

preg_split()

preg_split() splits a string by a regex pattern. More powerful than explode() for variable or multiple delimiters.

Example
<?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"]
Pro Tip

Use PREG_SPLIT_NO_EMPTY flag to automatically remove empty strings from the result array.