我有一个列表(作为字符串,比如$peoplelist),如下所示:
Name1
Name2
Name3
我想做的是将整个字符串分离成单独的元素(其中每一行对应一个新元素//,即元素1是"Name1",元素2是"Name2",等等),并将它们放入一个数组中(本质上,使用换行符作为分隔符,将该字符串拆分成单独的元件,放入唯一索引下的数组中)。
这就是我目前所拥有的:
# 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);
现在,使用上面提到的代码,这就是我得到的(输出):
array(1) { [0]=> string(71) "Name1
Name2
Name3
" }
根据我的输出,(据我所知)整个字符串(步骤1中的列表)被放在一个索引下的数组中,这意味着第二步并没有有效地完成我想要做的事情
我的问题是,如何将列表拆分为单独的元素(其中原始列表上的每一行都是唯一的元素),并将这些元素放置在数组中?
编辑:感谢大家的帮助!感谢localheinz提供的解决方案:)
注意:如果将来有人读到这篇文章,请确保列表的源文件包含原始数据-我的错误是使用了一个扩展名为.php的文件,其中包含html标记-这个html脚本干扰了索引过程。
使用file()
:
$arrayX = file(
'http://domain.tld/file-path/',
FILE_IGNORE_NEW_LINES
);
参考:
- http://php.net/manual/en/function.file.php
您可以在PHP中使用explode()。请参阅下面的代码,使用delimeter 'n
:拆分字符串
explode("'n", $string);
试试吧。
<?php
$peoplelist = file_get_contents('text.txt');
$arrayX[0] = $peoplelist;
echo "<pre>";
var_dump($arrayX);
?>
=>输出
array(1) {
[0]=>
string(19) "Name1
Name2
Name3"
}
使用带分隔符PHP_EOL的爆炸来表示跨平台。
$str = "Name1
Name2
Name3";
var_dump(explode(PHP_EOL,$str));
将导致
array(3) {
[0]=>
string(5) "Name1"
[1]=>
string(5) "Name2"
[2]=>
string(5) "Name3"
}