Advertisement
Intermediate PHP, Regular Expressions in PHP

How does preg_split let you break a string apart into an array using a regular expression as the delimiter, and how does this differ from PHP's simpler explode function?

Short answer

The preg_split function divides a string into an array of substrings based on matches of a regular expression pattern acting as the delimiter, which is significantly more flexible than the simpler explode function, since explode can only split on a single fixed literal string…

Save PHP mock interview
Advertisement
AModel answer
The preg_split function divides a string into an array of substrings based on matches of a regular expression pattern acting as the delimiter, which is significantly more flexible than the simpler explode function, since explode can only split on a single fixed literal string, while preg_split can split on a pattern representing multiple different possible delimiters at once, such as splitting on any combination of commas, semicolons, or extra whitespace.
$parts = preg_split('/[\s,;]+/', 'apple, banana;  cherry');
print_r($parts);
Real-world example
A data import script uses preg_split to correctly break apart a messy, inconsistently formatted input file where fields might be separated by a mix of commas, semicolons, or varying amounts of whitespace, something explode alone could not handle in a single call.
Likely follow-ups
  • What is the performance difference between preg_split and explode for simple, fixed delimiter cases?
  • How do you preserve the delimiters themselves within the resulting split array?
Related topics