How to split on delmiter using only the first delimiter

I have a variable that looks like this:

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

As you can see, these are basically values ​​broken into line breaks.

What I want to do is get the Option type, in this case "Dropdown" and save the rest of the values ​​in another line.

So,

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

The code above is what I tried, but this is what the lines came out like:

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

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

How do I do something like this?

The parameter type will always be the first part of the string, followed by the parameter values, each of which is divided into a string.

It is organized in this way, since it comes from user input, and it greatly facilitates user management.

+5
4

explode(), .

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

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

echo $bar;
+12
$values_array = explode("\n", $var);
$OptionType = $values_array[0];
unset($values_array[0]);
$OptionValues = implode("\n", $values_array);
+1

You can use array_shift to automatically turn off the first detonated element, and then join the rest.

<?
$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);
+1
source

you do not need hacking the array.

here is the code that 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"
+1
source

All Articles