Home > Net >  Remove first line from a variable string, while still keeping that first line
Remove first line from a variable string, while still keeping that first line

Time:12-05

i have an array and each value of that array contains a name that i need that's located in the first line, so i need to be able to take that name, while still deleting the first line.

This is what the array should look like

`[0] => "name texttexttexttexttexttexttexttext texttext"

[1] => "name texttexttexttexttexttexttexttext texttexttexttext"`

and what i expect to have is either have the name be the key of the array like so [name] => "texttexttexttexttexttext" [name] => "texttexttexttexttexttexttext" or another array that has only has the names in it.

I checked out other similar answered questions already but i hardly see how i could use explode and implode or any sort of regex on an array.

CodePudding user response:

Here is one way you can do it in PHP:

$names = array();
foreach ($array as $line) {
  // Use the explode function to split the line into words
  $words = explode(" ", $line);

  // The name will be the first word in the line, so we get it with array_shift
  $name = array_shift($words);

  // The rest of the words in the line are the text, so we use implode to join them back into a string
  $text = implode(" ", $words);

  // Add the name and text to the $names array
  $names[$name] = $text;
}

This will loop through each line in the original array, extract the name from the first word in the line, and add it to the $names array along with the rest of the text. The resulting array will have the name as the key and the text as the value.

Alternatively, if you only want an array of the names and not the text, you can just add the name to the $names array without the text:

$names = array();
foreach ($array as $line) {
  // Use the explode function to split the line into words
  $words = explode(" ", $line);

  // The name will be the first word in the line, so we get it with array_shift
  $name = array_shift($words);

  // Add the name to the $names array
  $names[] = $name;
}

This will create an array of names without the corresponding text.

  • Related