Multiline string to array

I have a list (as a string, say $ peoplelist) like this:

Name1
Name2
Name3

What I'm trying to do is split this whole line into separate elements (where each line corresponds to a new element // that is, element 1 is "name1", element 2 is "name2", etc.) and put them into an array (in essence, use line breaks as separators and separate this string into separate elements that must be placed in the array under unique indices).

This is what I have so far:

# Step 1 - Fetch the list
$peoplelist = file_get_contents('http://domain.tld/file-path/')
//The Contents of $peoplelist is stated at the top of this question.
//(The list of names in blue)

# Step 2 - Split the List, and put into an array
$arrayX = preg_split("/[\r\n]+/", $playerlist);
var_dump($arrayX);

Now, using the code mentioned above, this is what I get (output):

array(1) { [0]=> string(71) "Name1
Name2
Name3
" }

According to my result (from what I understand), the whole string (the list from step 1) is placed in an array under one index, which means that the second step does not do what I intend to do.

, ( ) ?

EDIT: , ! , localheinz, :)

.. - , , . .php, html - html script .

+4
4

file():

$arrayX = file(
    'http://domain.tld/file-path/',
    FILE_IGNORE_NEW_LINES
);

.:

+6

.

<?php

$peoplelist = file_get_contents('text.txt');
$arrayX[0] = $peoplelist;
echo "<pre>";
var_dump($arrayX);

?>

= > OUTPUT

  array(1) {
  [0]=>
  string(19) "Name1
   Name2
   Name3"
 }
+3

explode() PHP. . , \n:

explode("\n", $string);
+2

using explode with the PHP_EOL delimiter for cross platform.

$str = "Name1
Name2
Name3";

var_dump(explode(PHP_EOL,$str));

will result in

array(3) {
  [0]=>
  string(5) "Name1"
  [1]=>
  string(5) "Name2"
  [2]=>
  string(5) "Name3"
}
+2
source

Source: https://habr.com/ru/post/1622036/


All Articles