split function not working on new lines - php

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 \n is evaluated as a literal \n and not a newline character.
Only CASE3, with the double quotes, will evaluate \n as a newline.
Also, the function split() is deprecated. Try using explode() instead.

That's because '\n' not outputs new line, and not interpritate as new line, so in CMD too you don't pass new lines;
Also, split() is deprecated, use explode();

The big difference between using single quotes '' and double quotes "" are for automatic replacement inside of strings.
Using "" will enable replacement of variables and usage of escape sequences while '' doesn't support this.
$name = 'Mathieu';
$case1 = "Hi this is $name speaking\nPleased to meet you!";
echo $case1;
//Will result in
Hi this is Mathieu speaking
Pleased to meet you!
While using single quotes will yield:
$name = 'Mathieu';
$case1 = 'Hi this is $name speaking\nPleased to meet you!';
echo $case1;
//Will result in
Hi this is $name speaking\nPleased to meet you!
All escape sequences possible are:
\n Line feed (dec 13)
\r Carriage return (dec 10)
\t Tab (dec 8)
Relative to your question about line feeds, note that \n, \r, \r\n are using in different combination depending on the OS and information coming from a Windows OS usually features \r\n while linux only has \n. MacOS used to or still features only \r i think, not sure.

Single-quoted strings are not supposed to expand all the escape strings like /n.

Related

Explode text into array as per paragraph

I have the following text:
$test = 'Test This is first line
Test:123
This is Test';
I want to explode this string to an array of paragraphs. I wrote the following code but it is not working:
$array = explode('\n\n', $test);
Any idea what I'm missing here?
You might be on Windows which uses \r\n instead of \n. You could use a regex to make it universal with preg_split():
$array = preg_split('#(\r\n?|\n)+#', $test);
Pattern explanation:
( : start matching group 1
\r\n?|\n : match \r\n, \r or \n
) : end matching group 1
+ : repeat one or more times
If you want to split by 2 newlines, then replace + by {2,}.
Update: you might use:
$array = preg_split('#\R+#', $test);
This extensive answer covers the meaning of \R. Note that this is only supported in PCRE/perl. So in a sense, it's less cross-flavour compatible.
Your code
$array = explode('\n\n', $test);
should have \n\n enclosed in double quotes:
$array = explode("\n\n", $test);
Using single quotes, it looks through the variable $test for a literal \n\n. With double quotes, it looks for the evaluated values of \n\n which are two carriage returns.
Also, note that the end of line depends on the host operating system. Windows uses \r\n instead of \n. You can get the end of line for the operating system by using the predefined constant PHP_EOL.
Try double quotes
$array = explode("\n\n", $test);
did you have try this ?
$array = explode("\n", $test);
The easiest way to get this text into an array like you describe would be:
preg_match_all('/.+/',$string, $array);
Since /./ matches any char, except for line terminators, and the + is greedy, it'll match as many chars as possible, until a new-line is encountered.
Using preg_match_all ensures this is repeated for each line, too. When I tried this, the output looked like this:
array (
0 =>
array (
0 => '$test = \'Test This is first line',
1 => 'Test:123',
2 => 'This is Test\';',
),
)
Also note that line-feeds are different, depending on the environment (\n for *NIX systems, compared to \r\n for windows, or in some cases a simple \r). Perhaps you might want to try explode(PHP_EOL, $text);, too
You need to use double quotes in your code, such that the \n\n is actually evaluated as two lines. Look below:
'Paragraph 1\n\nParagraph 2' =
Paragraph 1\n\nParagraph 2
Whereas:
"Paragraph 1\n\nParagraph 2" =
Paragraph 1
Paragraph 2
Also, Windows systems use \r\n\r\n instead of \n\n. You can detect which line endings the system is using with:
PHP_EOL
So, your final code would be:
$paragraphs = explode(PHP_EOL, $text);

Trying to remove new lines and spaces using regex

I am attempting to remove some line breaks and spaces from a multiline string I have, such as the following:
Toronto (YTZ)
to
Montreal (YUL)
I tried doing:
$matched = preg_replace('/[\n]/', '', $string);
var_dump($matched);
but all it returns is:
Montreal (YUL)
I've tried all sorts of combinations of regular expressions, but it only ever seems to find what I specify, replace it, and display anything AFTER the matched expression.
I'm sure it's something simple, but I can't seem to figure it out.
Thanks in advance!
\n only represents "go to line" if it is between double quotes in PHP "\n"... Your regex should be "/[\n]/" not '/[\n]/'
Anyway, don't use a regular expression for that, but str_replace("\n",'',$string) instead. It's faster.
As Kash already noticed you, expression of new line in different OS can be different.
That's where PHP_EOL constant is used. This constant is defined depending on OS.
$string = str_replace(PHP_EOL, '', $string);
if string could be created on different machine, then it would be better to replace "\r" and "\n" separately
$string = str_replace(array("\r", "\n"), '', $string);
$str = preg_replace('/\n+(?=.)/', " ",
preg_replace('/^\s*/m', "",
$str));
Check this code here.

How to remove ANSI-Code (" ") from string in PHP

I have tried a lot but nothing is working. I want to import a XML-file with PHP. In some strings the customer puts some ANSI-Code Carrier Returns ("
"). I have tried to remove them with:
str_replace('\r', '', $xml->description);
I also tried it with "&\#13;", "\r\n", "\&\\#13\;" in the search but nothing works. Do you have any idea how to remove these linebreaks?
Thanks!
Since your XML processor is already handling de-entitying the entities, you'll be left over with plain ASCII \n or \r or \r\n. PHP does not handle \r or \n inside of single quotes. It only translates them to their respective characters (codes 10 and 13), when the \r and \n are inside of double quotes.
You just need to use "\n" or maybe "\r\n".
Should just be a simple case of:
str_replace('
', '', $xml->description);
Notice I haven't escaped the # with a \.
Actually, This runs just fine
$str = "&\#13;"; //just an example
echo str_replace("&\\#13;", "hello", $str);
Demo
This worked for me:
str_replace("\x13", '', $str);
I'm using the hexcode for that char.

How do you echo a string with every char in PHP?

I need to know if there's a way in PHP to echo a string with every char.
For instance
/n
and the likes.
Edit for clarification:
When I have a webform and I submit it and I have this text:
I am stupid
and I cannot
explain myself
The text would be like this:
I am stupid /n and I cannot /n explain myself
If I use:
nl2br
I get:
I am stupid <br /> and I cannot <br /> explain myself
Now I have users that input some messed up texts and I need to clean it and put it inside an array. I would love to be able to print to screen every special char such as /n.
I think he means that instead of seeing a newline when a string contains '\n' he wants to see the '\n' as two characters, a '\' and an 'n'.
json_encode works well for this purpose:
echo json_encode("spam\nand eggs");
>> "spam\nand eggs"
Assuming you mean to add \n to every character and $string contains the string you want to edit:
$strarray = str_split($string);
$string = "";
foreach($strarray as $char)
{
$string .= $char."\n";
}
echo $string;
After this $string will contain the original $string with a newline added after every character, and will be echoed. For this to be displayed, you'd have to surround it with <pre> though.
I think he wants to break string into chars and want to print each char in new line. is it ?

Is it possible in PHP to escape newlines in strings as in C?

In C you can continue a string literal in the next line escaping the newline character:
char* p = "hello \
new line.";
( My C is a bit rusty and this could be non 100% accurate )
But in php, the backslash is taking literally:
$p = "hello \
new line.";
I.E. the backslash character forms part of the string.
Is there a way to get the C behavior in PHP in this case?
Is it possible to simply concatenate your string like this:
$p = "hello " .
"new line.";
There's a few ways to do this in PHP that are similar, but no way to do it with a continuation terminator.
For starters, you can continue your string on the next line without using any particular character. The following is valid and legal in PHP.
$foo = 'hello there two line
string';
$foo = 'hello there two line
string';
The second example should one of the drawbacks of this approach. Unless you left jusity the remaining lines, you're adding additional whitespace to your string.
The second approach is to use string concatenation
$foo = 'hell there two line'.
'string';
$foo = 'hell there two line'.
'string';
Both example above will result in the string being created the same, in other words there's no additional whitespace. The trade-off here is you need to perform a string concatenation, which isn't free (although with PHP's mutable strings and modern hardware, you can get away with a lot of concatenation before you start noticing performance hits)
Finally there's the HEREDOC format. Similar to the first option, HEREDOC will allow you to break your strings over multiple lines as well.
$foo = <<<TEST
I can go to town between the the start and end TEST modifiers.
Wooooo Hoooo. You can also drop $php_vars anywhere you'd like.
Oh yeah!
TEST;
You get the same problems of leading whitespace as you would with the first example, but some people find HEREDOC more readable.
In PHP you can simply continue on a new line with a string.
eg.
<?php
$var = 'this is
some text
in a var';
?>
The short answer is that you cannot do it as easily as in C, you need to either concatenate (best):
$p = "This is a long".
" non-multiline string";
or remove the newlines afterwards (awful, don't do this):
$p = "This will contain the newlines
before this line";
//for instance str_replace() can remove the newlines

Categories