Split PHP Variable in to array

帅比萌擦擦* 提交于 2021-01-29 11:20:41

问题


A php variable contains

$string = "256 Engineering Maths-I 21 -1 21 F";

printing

$string

gives output

256 Engineering Maths-I 21 -1 21 F

this variable should split in to

$n[0] = "256";
$n[1] = "Engineering Maths-I";
$n[2] = "21";
$n[3] = "-1";
$n[4] = "21";
$n[5] = "F";

I have tried with

$n = explode(" ", $string);

but it is splitting in to 2 parts

Please help me


回答1:


What you are probably looking at is a tab separated string

Do this

$n = explode("\t", $string);

UPDATE The answer was that the text was delimited by a newline. so

$n = explode("\n", $string); 

The browser's behavior of collapsing whitespace to a single space was masking what was really happening.




回答2:


You can also try to split on whitespace:

$n = preg_split('/\s+/', $string);


来源:https://stackoverflow.com/questions/17755910/split-php-variable-in-to-array

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