Talon
Talon

Reputation: 4995

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.

Upvotes: 6

Views: 4276

Answers (4)

Taha Paksu
Taha Paksu

Reputation: 15616

you don't need the array exploding.

here's the code which will work for you:

$var = "Dropdown\nValue 1\nValue 2\nValue 3\n";
$the_first_element = substr($var,0,strpos($var,"\n"));
$what_i_want = substr($var,strpos($var,"\n")+1);

//returns :
//"Dropdown"
//"Value1\nValue2\nValue3\n"

Upvotes: 1

Bryan
Bryan

Reputation: 6752

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);

Upvotes: 1

Sampson
Sampson

Reputation: 268344

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;

Upvotes: 20

Aaron W.
Aaron W.

Reputation: 9299

$values_array = explode("\n", $var);
$OptionType = $values_array[0];
unset($values_array[0]);
$OptionValues = implode("\n", $values_array);

Upvotes: 1

Related Questions