This function works similarly to explode() but uses a regular expression (regex) to split the string.

The first example here will split the string on whitespace OR the string “ry”. I’m using the tilde (~) here as the regex delimiter. Commonly you’ll see a slash used but I find this nicer to look at.

Note the empty strings in the resulting array. This is from splitting the segment “cry ” (and again with “every “) on “ry” then on the space. Nothing is in between there and that’s what it gives you - an empty string.

The second example splits on a whitespace character followed by the character “e”.

$str = "These eyes cry every night for you.";
 
$arr = preg_split('~\s|ry~', $str);
/*
array (
  0 => 'These',
  1 => 'eyes',
  2 => 'c',
  3 => '',
  4 => 'eve',
  5 => '',
  6 => 'night',
  7 => 'for',
  8 => 'you.'
)
*/
 
$arr = preg_split('~\se~', $str);
/*
array (
  0 => 'These',
  1 => 'yes cry',
  2 => 'very night for you.'
)
*/