Php multiple delimiters in explode

PhpExplode

Php Problem Overview


I have a problem, I have a string array, and I want to explode in different delimiter. For Example

$example = 'Appel @ Ratte';
$example2 = 'apple vs ratte'

and I need an array which is explode in @ or vs.

I already wrote a solution, but If everybody have a better solution please post here.

private function multiExplode($delimiters,$string) {
	$ary = explode($delimiters[0],$string);
	array_shift($delimiters);
	if($delimiters != NULL) {
		if(count($ary) <2)						
			$ary = $this->multiExplode($delimiters, $string);
	}
	return  $ary;
}

Php Solutions


Solution 1 - Php

Try about using:

$output = preg_split('/ (@|vs) /', $input);

Solution 2 - Php

You can take the first string, replace all the @ with vs using str_replace, then explode on vs or vice versa.

Solution 3 - Php

function multiexplode ($delimiters,$string) {
    
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";


$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also 
//    [4] =>  this one too 
//    [5] => )
// )

Source: php@metehanarslan at php.net

Solution 4 - Php

How about using strtr() to substitute all of your other delimiters with the first one?

private function multiExplode($delimiters,$string) {
	return explode(
		$delimiters[0],
		strtr(
			$string,
			array_combine(
				array_slice(	$delimiters, 1	),
				array_fill(
					0,
					count($delimiters)-1,
					array_shift($delimiters)
				)
			)
		)
	);
}

It's sort of unreadable, I guess, but I tested it as working over here.

One-liners ftw!

Solution 5 - Php

Wouldn't strtok() work for you?

Solution 6 - Php

Simply you can use the following code:

$arr=explode('sep1',str_replace(array('sep2','sep3','sep4'),'sep1',$mystring));

Solution 7 - Php

You can try this solution.... It works great

function explodeX( $delimiters, $string )
{
    return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';

$exploded = explodeX( array('&', ',', '|' ), $list );

echo '<pre>';
print_r($exploded);
echo '</pre>';

Source : http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

Solution 8 - Php

How about this?

/**
 * Like explode with multiple delimiters. 
 * Default delimiters are: \ | / and ,
 *
 * @param string $string String that thould be converted to an array.
 * @param mixed $delimiters Every single char will be interpreted as an delimiter. If a delimiter with multiple chars is needed, use an Array.
 * @return array. If $string is empty OR not a string, return false
 */
public static function multiExplode($string, $delimiters = '\\|/,') 
{
  $delimiterArray = is_array($delimiters)?$delimiters:str_split($delimiters);
  $newRegex = implode('|', array_map (function($delimiter) {return preg_quote($delimiter, '/');}, $delimiterArray));
  return is_string($string) && !empty($string) ? array_map('trim', preg_split('/('.$newRegex.')/', $string, -1, PREG_SPLIT_NO_EMPTY)) : false;
}

In your case you should use an Array for the $delimiters param. Then it is possible to use multiple chars as one delimiter.

If you don't care about trailing spaces in your results, you can remove the array_map('trim', [...] ) part in the return row. (But don't be a quibbler in this case. Keep the preg_split in it.)

Required PHP Version: 5.3.0 or higher.

You can test it here

Solution 9 - Php

I do it this way...

public static function multiExplode($delims, $string, $special = '|||') {

    if (is_array($delims) == false) {
        $delims = array($delims);
    }
    
    if (empty($delims) == false) {
        foreach ($delims as $d) {
            $string = str_replace($d, $special, $string);
        }
    }

    return explode($special, $string);
}

Solution 10 - Php

You are going to have some problems (what if you have this string: "vs @ apples" for instance) using this method of sepparating, but if we start by stating that you have thought about that and have fixed all of those possible collisions, you could just replace all occurences of $delimiter[1] to $delimiter[n] with $delimiter[0], and then split on that first one?

Solution 11 - Php

If your delimiter is only characters, you can use strtok, which seems to be more fit here. Note that you must use it with a while loop to achieve the effects.

Solution 12 - Php

This will work:

$stringToSplit = 'This is my String!' ."\n\r". 'Second Line';
$split = explode (
  ' ', implode (
    ' ', explode (
      "\n\r", $stringToSplit
    )
  )
);

As you can see, it first glues the by \n\r exploded parts together with a space, to then cut it apart again, this time taking the spaces with him.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOHL&#193;L&#193;View Question on Stackoverflow
Solution 1 - PhpSergeSView Answer on Stackoverflow
Solution 2 - PhpJohn BallingerView Answer on Stackoverflow
Solution 3 - Phpparts2View Answer on Stackoverflow
Solution 4 - PhpAubryView Answer on Stackoverflow
Solution 5 - PhpMchlView Answer on Stackoverflow
Solution 6 - PhpSamer AtaView Answer on Stackoverflow
Solution 7 - PhpMayur ChauhanView Answer on Stackoverflow
Solution 8 - PhpA.F.View Answer on Stackoverflow
Solution 9 - PhpVaciView Answer on Stackoverflow
Solution 10 - PhpNanneView Answer on Stackoverflow
Solution 11 - PhpHoàng LongView Answer on Stackoverflow
Solution 12 - PhpXesauView Answer on Stackoverflow