preg_split() Magic

../_images/preg_split.png

Most of the time, explode() is sufficient to split a string with a static separator. Otherwise, there is preg_split().

preg_split() uses a regex to split the string. This allows for multiple and complex separators to be used in the same call.

preg_split() accepts empty regex, to split strings with nothing: it turns a string into an array. It might require the PREG_SPLIT_NO_EMPTY option, to avoid trailing elements.

preg_split() has a PREG_SPLIT_DELIM_CAPTURE option, to collect the separators along the parsing. Since it might be complex, it is important to get them for further processing.

preg_split(), just like explode(), has a limit parameter, to stop processing the string, once a number of string has been found. This is perfect to prevent PHP from processing too much, as long as a number of expected strings can be predicted.

explode() is faster preg_split(), so use it for the simple and most common cases.

See Also

PHP Error Messages

PHP Features