Using preg_split() to explode() by multiple delimiters in PHP

Just a quick note here. To explode()  a string using multiple delimiters in PHP you will have to make use of the regular expressions. Use pipe character to separate your delimiters.

There are also various flags you can use as optional:

  • PREG_SPLIT_NO_EMPTY  – To return only non-empty pieces.
  • PREG_SPLIT_DELIM_CAPTURE – To capture and return the parenthesized expression in the delimiter.
  • PREG_SPLIT_OFFSET_CAPTURE – To return the appendant string offset for every occurring match.

Here is a simple example of usage:

…and this is the output:

Now let’s put everything back together in a nice form.

Enjoy this simple, yet powerful way to split a string by multiple delimiters in PHP. You can further read about the preg_split()  function on the PHP documentation site here

Leave a Reply

Your email address will not be published. Required fields are marked *