Split text using multiple delimiters into an array of trimmed values

I’ve got a group of strings which I need to chunk into an array. The string needs to be split on either /, ,, with, or &.

Unfortunately it is possible for a string to contain two of the strings which needs to be split on, so I can’t use split() or explode().

For example, a string could say first past/ going beyond & then turn, so I am trying to get an array that would return:

array('first past', 'going beyond', 'then turn')

The code I am currently using is

$splittersArray=array('/', ',', ' with ','&');
foreach($splittersArray as $splitter){
    if(strpos($string, $splitter)){
        $splitString = split($splitter, $string);
        foreach($splitString as $split){

I can’t seem to find a function in PHP that allows me to do this. Do I need to be passing the string back into the top of the funnel, and continue to go through the foreach() after the string has been split again and again?

This doesn’t seem very efficient.

Answer

Use a regular expression and preg_split.

In the case you mention, you would get the split array with:

$splitString = preg_split('/(/|,| with |&/)/', $string);

Leave a Reply

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