Search code examples
phpregexsplitpreg-split

Split PHP Variable in to array


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


Solution

  • 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.