explode() doesn't separate a string by spaces?

我们两清 提交于 2019-12-10 18:09:13

问题


I am attempting to open a text file and explode the list of names within into an array but when I var_dump the new array I get this:

array(1) { [0]=> string(61) "name name name name " }

The entire contents of the list goes into one single key field in the array.

This is the code I'm using:

$ingame_list = file_get_contents('../../../../home/folder/folder/list.txt');
$newarray = explode(" ", $ingame_list);
var_dump($newarray);

How can I get each name to be in its own key field within the new array?


回答1:


tl;dr Your list is separated by something other than simple spaces - most likely multiple adjacent whitespace characters. You're actually seeing an HTML rendering of the data, in which multiple adjacent whitespace characters are displayed as one.

Note the string(61) in the results of var_dump(). var_dump() reports the type, length, and content of a variable (in the case of a string). That string(61) means there are 61 characters in your string. So, if you are really getting back the string "name name name name ", this implies there are characters that you are not seeing here. This could be because of the way whitespace displays in HTML: tabs, newlines, and other whitespace characters all look like simple spaces. Are you sure the text is separated by spaces, not tabs or other whitespace?

explode() will only split the string on exact matches to the specified character/string. If the text is separated by \t, \n, \r, or other non-printing characters, your explode() statement won't work. For example, if you have this:

name    name    name

(pretend those are tab characters above), then your explode() doesn't find any plain old space (, character value 32) characters.

How to Fix This

Based on your comments below, your data contains newline (\n) characters, not plain spaces. You need to replace the second line of your code with this:

$newarray = explode("\n", $ingame_list);



回答2:


If they are separated by newlines then you don't even need explode:

$newarray = file('../../../../home/folder/folder/list.txt');


来源:https://stackoverflow.com/questions/20430869/explode-doesnt-separate-a-string-by-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!