By default, the PHP explode() function does not allow specifying multiple delimiters. However, there are other ways in which you achieve the same result:
Using str_replace() and explode()
You can make all the delimiters in the string the same using str_replace() by passing an array of delimiters as the first argument to the function. After that you can use explode() as you normally would on the resulting string. For example:
$delimiters = ['.', '!', '?']; $str = 'foo! bar? baz.'; $newStr = str_replace($delimiters, $delimiters[0], $str); // 'foo. bar. baz.' $arr = explode($delimiters[0], $newStr); echo print_r($arr, true); // ['foo', 'bar', 'baz', '']
If you want to remove empty values from the matches, then you can use the array_filter() function on the resulting array like so:
$delimiters = ['.', '!', '?']; $str = 'foo! bar? baz.'; $newStr = str_replace($delimiters, $delimiters[0], $str); // 'foo. bar. baz.' $arr = explode($delimiters[0], $newStr); $filteredArr = array_filter($arr); echo print_r($filteredArr, true); // ['foo', 'bar', 'baz']
Please note that the array_filter() function preserves the array keys (which may result in gaps in an indexed array). Reindexing the array should be possible with array_values().
Using preg_split()
Instead of using the explode() function, you could use preg_split(). With it you can specify a regular expression with multiple delimiters and split a string into an array. For example:
$str = 'foo! bar? baz.';
$arr = preg_split('/[.|!|?]/', $str);
echo print_r($arr, true); // ['foo', bar, baz, '']
If you want to remove non-empty values from the matches, then you can simply pass in the PREG_SPLIT_NO_EMPTY flag as the fourth argument to preg_split() like so:
$str = 'foo! bar? baz.';
$arr = preg_split('/[.|!|?]/', $str, -1, PREG_SPLIT_NO_EMPTY);
echo print_r($arr, true); // ['foo', bar, baz]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.