Search code examples
phppreg-split

preg_split() with strings containing '<'


I parsing a license key list in php. Unfortantly the results are not like expected. It seems that the problem occurs by the special character '<'. Would be nice if somebody have an idea of possible solutions.

$file_content = '
HM$WN*G&Z58CY8FPUA
F*QZHZGK#&*@*492&T
JJKXP<GZRPKGS7J!EW
P8ZHZ<GCNNR6X=Z7PW
C6HXQFGJ*Y2+#SDZT9
BYYYMEGMQ73G5K#U7F
P>+F=GG7F*U#<RT!6H
B+ZZYTGX&LF6@6XUXU
X&PHNAGN+X><NZYN#9';

$file_array = preg_split("/\n/", $file_content);

echo '<pre>';
print_r($file_array);

OUTPUT

[0] => 
[1] => HM$WN*G&Z58CY8FPUA
[2] => F*QZHZGK#&*@*492&T
[3] => JJKXP P8ZHZ C6HXQFGJ*Y2+#SDZT9
[6] => BYYYMEGMQ73G5K#U7F
[7] => P>+F=GG7F*U# B+ZZYTGX&LF6@6XUXU
[9] => X&PHNAGN+X>

Solution

  • Your split works as it should be, only thing is that browser converts those symbols to tags and causing that. You can check that by running this (I used htmlentities):

    <?php
    $file_content = '
    HM$WN*G&Z58CY8FPUA
    F*QZHZGK#&*@*492&T
    JJKXP<GZRPKGS7J!EW
    P8ZHZ<GCNNR6X=Z7PW
    C6HXQFGJ*Y2+#SDZT9
    BYYYMEGMQ73G5K#U7F
    P>+F=GG7F*U#<RT!6H
    B+ZZYTGX&LF6@6XUXU
    X&PHNAGN+X><NZYN#9';
    
    $file_array = preg_split("/\n/", $file_content);
    
    array_map("HTMLescape", $file_array);
    
    function HTMLescape($a) {
        echo "<pre>".htmlentities($a)."</pre>";    
    }
    

    Output:

    HM$WN*G&Z58CY8FPUA
    F*QZHZGK#&*@*492&T
    JJKXP<GZRPKGS7J!EW
    P8ZHZ<GCNNR6X=Z7PW
    C6HXQFGJ*Y2+#SDZT9
    BYYYMEGMQ73G5K#U7F
    P>+F=GG7F*U#<RT!6H
    B+ZZYTGX&LF6@6XUXU
    X&PHNAGN+X><NZYN#9
    

    Moreover, for just splitting this line, as @Marcin Orlowski pointed, you can opt for explode which is faster.