Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split by a delmiter by first delimiter only

I have a variable that looks like this:

$var = "Dropdown\n
  Value 1\n
  Value 2\n
  Value 3\n";

As you can see it's basically values broken by line breaks.

What I want to do is get the Option Type, in this case "Dropdown" and store the rest of the values in another string.

So

list($OptionType, $OptionValues) = explode("\n", $var);

The code above is what I tried but this is what the strings came out as:

$OptionType = 'Dropdown'; //Good
$OptionValues = 'Value 1';  // Only got the first value

I want $OptionValues to be like this: $OptionValues = "Value 1\nValue 2\nValue 3\n";

How would I do something like that?

The Option Type is always going to be the first part of the string followed by option values each seperated by a linebreak.

It's organized this way as it comes from user-input and it makes it much easier on the user to handle.

like image 518
Talon Avatar asked May 05 '12 23:05

Talon


3 Answers

You need to use the third argument of explode(), which sets the limit.

$var = "Dropdown\n
  Value 1\n
  Value 2\n
  Value 3\n";

list( $foo, $bar ) = explode( "\n", $var, 2 );

echo $bar;
like image 118
Sampson Avatar answered Nov 14 '22 21:11

Sampson


$values_array = explode("\n", $var);
$OptionType = $values_array[0];
unset($values_array[0]);
$OptionValues = implode("\n", $values_array);
like image 27
Aaron W. Avatar answered Nov 14 '22 22:11

Aaron W.


You can use array_shift to automatically pop off the first exploded element, and then join the remaining.

<?
$var = "Dropdown\nValue 1\nValue 2\nValue 3\n";

$exploded = explode("\n", $var);
$OptionType = array_shift($exploded);
$OptionValues = join("\n", $exploded);

echo $OptionType . "\n";
print_r($OptionValues);
like image 30
Bryan Avatar answered Nov 14 '22 23:11

Bryan