Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Line String to an Array

Tags:

arrays

string

php

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

Name1
Name2
Name3

What I'm trying to do is separate that entire string into separate elements (where each line corresponds to a new element // i.e. Element 1 is "Name1", Element 2 is "Name2", etc.) and place them into an array (essentially, use lines breaks as delimiters and split that string into separate elements to be put into an array under unique indexes).

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 output, (from what I understand) the entire string (the list from Step 1) is being placed into an array under a single index, which means that the second step isn't effectively doing what I intend it to do.

My question is, how do I split the list into separate elements (where each separate line on the original list is a unique element) and place these elements in an array?

EDIT: Thanks for all the help, everyone! And thank you, localheinz, for the solution :)

NOTE: If anyone reads this in the future, please ensure that your source file for the list contains raw data - my mistake was using a file with .php extension that contained html tags - this html script interfered with the indexing process.

like image 769
Ash Avatar asked Dec 05 '22 19:12

Ash


1 Answers

Use file():

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

For reference, see:

  • http://php.net/manual/en/function.file.php
like image 168
localheinz Avatar answered Dec 09 '22 15:12

localheinz