Exploding by Array of Delimiters

Exploding by Array of Delimiters

Use preg_split() with an appropriate regex.

explode multiple delimiters in php

I would go for preg_split like below

<?php

$list = "{flower},{animals},{food},{people},{trees}";
$array = preg_split('/[},{]/', $list, 0, PREG_SPLIT_NO_EMPTY);
print_r($array);
?>

The output is

Array
(
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)

exploding string with multiple delimiter

Tokens all the way down...

<?php

$str = '1-a,2-b,3-c';
$token = '-,';

if($n = strtok($str, $token))
$array[$n] = strtok($token);
while($n = strtok($token))
$array[$n] = strtok($token);

var_export($array);

Output:

array (
1 => 'a',
2 => 'b',
3 => 'c',
)

Or perhaps more terse without the first if...:

$array = [];
while($n = $array ? strtok($token) : strtok($str, $token))
$array[$n] = strtok($token);

Exploding an array in PHP with three delimiters

What you got there looks like CSV, just not comma separated, but using a pipe. The function str_getcsv should be working in that case:

$inputString = <<<EOS
the_first|Little Detail|Some Large Details with a para of text
the_second|Little Detail|Some Large Details with a para of text
the_third|Little Detail|Some Large Details with a para of text
EOS;

$outputArray = str_getcsv( $inputString, '|');

Exploding a String with Two Delimiters

My preferred solution would be to use preg_split, but since the question explicitly forbids the use of regex, how about just doing this:

$line = explode("#", str_replace("@", "#", $line));

So basically, just replace all occurrences of delimiter 1 with delimiter 2 and then split on delimiter 2.

Php multiple delimiters in explode

Try about using:

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

How can I explode a string by multiple delimiters and also keep the delimiters?

This should work for you:

Just use preg_split() and set the flags to keep the delimiters. E.g.

<?php

$string = "(2.8 , 3.1) → (↓↓2.4 , ↓3.0)";
$arr = preg_split("/(↑↑|↑|↓↓|↓)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($arr);

?>

output:

Array
(
[0] => (2.8 , 3.1) → (
[1] => ↓↓
[2] => 2.4 ,
[3] => ↓
[4] => 3.0)
)

Explode string by multiple delimiters into multi-dimensional array php

<?php

function expl($str, $charlist = '|')
{
if (!$charlist) {
return $str;
}
$char = $charlist[0];
$matrix = explode($char, $str);
for ($i = 0; $i < sizeof($matrix); $i++) {
$matrix[$i] = expl($matrix[$i], substr($charlist, 1));
}
return $matrix;
}
echo "<pre>";
print_r(expl("A~a1~a2|B~b1~b2", '|~'));
echo "</pre>";

that would be something like this...
use recursion!
the first level will get the first matrix, doing something like this

$matrix[0] = "A~a1~a2";
$matrix[1] = "B~b1~b2";

and then, the recursion will do the second part, which will make each string become the array of strings, that will become the array of strings until there's no more separators.



Related Topics



Leave a reply



Submit