Hi I have simple split script and I am splitting a string on new line that has many new lines characters in it. Here is the code :
<?php
$string = $argv[1]; // CASE 1: COMMAND LINE ARGUMENT.
echo "String is : $string\n";
//$string = 'Hello Shakir\nOkay Shakir\nHow are you ?'; //CASE2: SINGLE QUOTE.
$string = "Hello Shakir\nOkay Shakir\nHow are you ?"; //CASE 3: DOUBLE QUOTE.
$lines = array();
$lines = split("\n", $string);
foreach ( $lines as $line ) {
echo "line is : $line\n";
//var_dump($line);
}
?>
It works fine when I use CASE 3 in the code, but it doesnt work when I use either CASE1 or CASE 2 (Only CASE 3 works fine). Can anybody please shed some light on this ?
This is how I run it on command line(linux machine) :
php my_script.php "Hello Shakir\nOkay Shakir\nHow are you ?"
In this case when I print $argv[1], it prints the entire string but it treats it same as CASE2 (with single quotes).
UPDATE :
Many of you have said what the cause of the issue is and not the answer to it. However, knowing the cause helped me fix it. So the answer is :
ANSWER :
Instead of using \n in double quotes (“\n”), use single quotes (‘\n’) :
$lines = split('\n', $string);
OR
$lines = explode('\n', $string);
However split counts ‘\’ also as a character and I dont know why. But explode is correct. Since split is deprecated I dont have done much research on this.
Thank you for all who let me know that split is deprecated.
CASE1 and CASE2 will not work for a simple reason, because
\nis evaluated as a literal\nand not a newline character.Only CASE3, with the double quotes, will evaluate
\nas a newline.Also, the function
split()is deprecated. Try usingexplode()instead.