Removing newlines from ob_get_clean() output - php

ok i do have this following codes
<?php
ob_start();
?>
codepad is an
online compiler/interpreter,
and a simple collaboration tool.
Paste
your code below,
and codepad wi
ll run
it and give you a short
URL you can use to share
it in chat or email
<?php
$str = str_replace('\r\n','',trim(ob_get_clean()));
echo $str;
?>
and you can see how it works here
http://codepad.org/DrOmyoY9
now what i want here is to remove the newlines from the stored output of the ob_get_clean().
I almost looked around the internet on how to remove newlines in the strings and that's the common and fastest method to remove the newlines aside from using the slowly preg_replace().
Why this happens? is this already a bug? or i just missed something?

\r\n is windows style, but if the user using linux or mac, it would be different . so best solution is:
$str = str_replace(array("\r","\n"),'',trim(ob_get_clean()));

I think u miss one thing, it should be :
$str = str_replace("\r\n",'',trim(ob_get_clean()));
using double quotes not single quotes

Related

Exploding CSV file on new line [duplicate]

Simple, right? Well, this isn't working :-\
$skuList = explode('\n\r', $_POST['skuList']);
Best Practice
As mentioned in the comment to the first answer, the best practice is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).
$skuList = explode(PHP_EOL, $_POST['skuList']);
PHP provides a lot of other very useful constants that you can use to make your code system independent, see this link to find useful and system independent directory constants.
Warning
These constants make your page system independent, but you might run into problems when moving from one system to another when you use the constants with data stored on another system. The new system's constants might be different from the previous system's and the stored data might not work anymore. So completely parse your data before storing it to remove any system dependent parts.
UPDATE
Andreas' comment made me realize that the 'Best Practice' solution I present here does not apply to the described use-case: the server's EOL (PHP) does not have anything to do with the EOL the browser (any OS) is using, but that (the browser) is where the string is coming from.
So please use the solution from #Alin_Purcaru to cover all your bases:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Cover all cases. Don't rely that your input is coming from a Windows environment.
$skuList = preg_split("/\\r\\n|\\r|\\n/", $_POST['skuList']);
or
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Try "\n\r" (double quotes) or just "\n".
If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".
Lots of things here:
You need to use double quotes, not single quotes, otherwise the escaped characters won't be escaped.
The normal sequence is \r\n, not \n\r.
Depending on the source, you may just be getting \n without the \r (or even in unusual cases, possibly just the \r)
Given the last point, you may find preg_split() using all the possible variants will give you a more reliable way of splitting the data than explode(). But alternatively you could use explode() with just \n, and then use trim() to remove any \r characters that are left hanging around.
try
explode(chr(10), $_POST['skuList']);
this php function explode string by newline
Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.pay attention that empty lines will be ignored
function splitNewLine($text) {
$code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
return explode("\n",$code);
}
example
$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );
output
Array
(
[0] => salam
[1] => man khobam
[2] => to chi
[3] => che khabar
[4] => bashe baba raftam
)
It doesn't matter what your system uses as newlines if the content might be generated outside of the system.
I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.
https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n
Code: (Demo)
$text = "one\ntwo\r\nthree\rfour\r\n\nfive";
var_export(preg_split('~\R~', $text));
Output:
array (
0 => 'one',
1 => 'two',
2 => 'three',
3 => 'four',
4 => '',
5 => 'five',
)
Place the \n in double quotes:
explode("\n", $_POST['skuList']);
In single quotes, if I'm not mistaken, this is treated as \ and n separately.
To preserve line breaks (as blank items in the array):
$skuList = preg_split('/\r\n|\n\r|\r|\n/', $_POST['skuList']);`
This handles the unusual \n\r as well as the usual \n\r, \n and \r. Note that the solution from #Alin_Purcaru is very similar, but doesn't handle \n\r.
To remove line breaks (no blank items in the array):
$skuList = preg_split('/[\r\n]+/', $_POST['skuList']);
PHP Tests
These expressions has been tested on the following OS'es: ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15 and in the following PHP versions: 8.0, 7.4, 7.3, 7.2, 7.1, 7.0
Here is the PHP test class:
https://github.com/rosell-dk/exec-with-fallback/blob/main/tests/LineSplittingTest.php
And a successful CI run on a project that runs those tests:
https://github.com/rosell-dk/exec-with-fallback/actions/runs/1520070091
Javascript demos of the principle
Here are some javascript demos of similar regular expressions (I'm using N and R instead of \n and \r).
Preserve linebreaks demo: https://regexr.com/6ahvl
Remove linebreaks demo: https://regexr.com/6ai0j
PS: There is currently a bug in regexr which causes it to show "Error" when first loaded. Editing the expression makes the error go away
For a new line, it's just
$list = explode("\n", $text);
For a new line and carriage return (as in Windows files), it's as you posted. Is your skuList a text area?
Have you tried using double quotes?
Not perfect but I think it must be safest. Add nl2br:
$skuList = explode('<br />', nl2br($_POST['skuList']));
As easy as it seems
$skuList = explode('\\n', $_POST['skuList']);
You just need to pass the exact text "\n" and writing \n directly is being used as an Escape Sequence. So "\\" to pass a simple backward slash and then put "n"
PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Try this:
$myString = "Prepare yourself to be caught
You in the hood gettin' shot
We going throw hell of blows
got my whole frame froze";
$myArray = explode(PHP_EOL, $myString);
print_r($myArray);
First of all, I think it's usually \r\n, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n.
Losing line breaks from posting from input textboxes?
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
this keeps the linebreaks intact in the POST.
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];
Try this:
explode(PHP_EOF, $lines);
Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:
$skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
$skuList = str_replace("\\n\\r", "\n", $skuList);
$skuList = preg_split("/\n/", $skuList);
print_r($skuList);
This method always works for me:
$uniquepattern="##$;?:~#abcz"//Any set of characters which you dont expect to be present in user input $_POST['skuList'] better use atleast 32 charecters.
$skuList=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['skuList'])));

How to convert special characters in HTML using PHP?

Im looking to convert special characters like smart quotes to HTML entities but without converting other HTML markup because I need HTML markup to work.
For example, convert <div>NVH “noise”</div> to <div>NVH “noise” issues<div>
Its strange that if I log this on my local environment I get “noise” with smartquotes but on server I got ?noise?. My local runs LAMP with php56. server ran 54 and 55. I upgraded to 56 still no luck. I think either something in php configuration or among other things. Same exact code.
For only one translation of the smart quotes, or for some characters and not others, str_replace is probably the only way to go:
$string = str_replace(array('“','”'), array('“','”'), $string);
Try php htmlspecialchars method
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>

PHP - Strip Tags allow "<3" text hearts

Hey Guys, I usually come to StackOverflow for my php coding answers, although this time I could not seem to find one.
I am creating a social networking type website that requires lots of text entering and data checking. Everything seems good and the other day I was testing some characters users may enter and its seems that if I try to insert a '<3' it says its empty.
<?php
$text = "<3";
$clean = strip_tags($text);
echo $clean; // prints out nothing..
?>
Use htmlspecialchars instead strip_tags.
"<3" will be break your HTML when you output it directly.
May you replace it with an (Heart)Image or other HTML- Tag( with css heart property) , like you would do with Smileys.

Explode PHP string by new line

Simple, right? Well, this isn't working :-\
$skuList = explode('\n\r', $_POST['skuList']);
Best Practice
As mentioned in the comment to the first answer, the best practice is to use the PHP constant PHP_EOL which represents the current system's EOL (End Of Line).
$skuList = explode(PHP_EOL, $_POST['skuList']);
PHP provides a lot of other very useful constants that you can use to make your code system independent, see this link to find useful and system independent directory constants.
Warning
These constants make your page system independent, but you might run into problems when moving from one system to another when you use the constants with data stored on another system. The new system's constants might be different from the previous system's and the stored data might not work anymore. So completely parse your data before storing it to remove any system dependent parts.
UPDATE
Andreas' comment made me realize that the 'Best Practice' solution I present here does not apply to the described use-case: the server's EOL (PHP) does not have anything to do with the EOL the browser (any OS) is using, but that (the browser) is where the string is coming from.
So please use the solution from #Alin_Purcaru to cover all your bases:
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Cover all cases. Don't rely that your input is coming from a Windows environment.
$skuList = preg_split("/\\r\\n|\\r|\\n/", $_POST['skuList']);
or
$skuList = preg_split('/\r\n|\r|\n/', $_POST['skuList']);
Try "\n\r" (double quotes) or just "\n".
If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".
Lots of things here:
You need to use double quotes, not single quotes, otherwise the escaped characters won't be escaped.
The normal sequence is \r\n, not \n\r.
Depending on the source, you may just be getting \n without the \r (or even in unusual cases, possibly just the \r)
Given the last point, you may find preg_split() using all the possible variants will give you a more reliable way of splitting the data than explode(). But alternatively you could use explode() with just \n, and then use trim() to remove any \r characters that are left hanging around.
try
explode(chr(10), $_POST['skuList']);
this php function explode string by newline
Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.pay attention that empty lines will be ignored
function splitNewLine($text) {
$code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
return explode("\n",$code);
}
example
$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );
output
Array
(
[0] => salam
[1] => man khobam
[2] => to chi
[3] => che khabar
[4] => bashe baba raftam
)
It doesn't matter what your system uses as newlines if the content might be generated outside of the system.
I am amazed after receiving all of these answers, that no one has simply advised the use of the \R escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R provides the most succinct and direct approach.
https://www.php.net/manual/en/regexp.reference.escape.php#:~:text=line%20break:%20matches%20\n,%20\r%20and%20\r\n
Code: (Demo)
$text = "one\ntwo\r\nthree\rfour\r\n\nfive";
var_export(preg_split('~\R~', $text));
Output:
array (
0 => 'one',
1 => 'two',
2 => 'three',
3 => 'four',
4 => '',
5 => 'five',
)
Place the \n in double quotes:
explode("\n", $_POST['skuList']);
In single quotes, if I'm not mistaken, this is treated as \ and n separately.
To preserve line breaks (as blank items in the array):
$skuList = preg_split('/\r\n|\n\r|\r|\n/', $_POST['skuList']);`
This handles the unusual \n\r as well as the usual \n\r, \n and \r. Note that the solution from #Alin_Purcaru is very similar, but doesn't handle \n\r.
To remove line breaks (no blank items in the array):
$skuList = preg_split('/[\r\n]+/', $_POST['skuList']);
PHP Tests
These expressions has been tested on the following OS'es: ubuntu-20.04, ubuntu-18.04, windows-2022, windows-2019, windows-2016, macos-11, macos-10.15 and in the following PHP versions: 8.0, 7.4, 7.3, 7.2, 7.1, 7.0
Here is the PHP test class:
https://github.com/rosell-dk/exec-with-fallback/blob/main/tests/LineSplittingTest.php
And a successful CI run on a project that runs those tests:
https://github.com/rosell-dk/exec-with-fallback/actions/runs/1520070091
Javascript demos of the principle
Here are some javascript demos of similar regular expressions (I'm using N and R instead of \n and \r).
Preserve linebreaks demo: https://regexr.com/6ahvl
Remove linebreaks demo: https://regexr.com/6ai0j
PS: There is currently a bug in regexr which causes it to show "Error" when first loaded. Editing the expression makes the error go away
For a new line, it's just
$list = explode("\n", $text);
For a new line and carriage return (as in Windows files), it's as you posted. Is your skuList a text area?
Have you tried using double quotes?
Not perfect but I think it must be safest. Add nl2br:
$skuList = explode('<br />', nl2br($_POST['skuList']));
As easy as it seems
$skuList = explode('\\n', $_POST['skuList']);
You just need to pass the exact text "\n" and writing \n directly is being used as an Escape Sequence. So "\\" to pass a simple backward slash and then put "n"
PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Try this:
$myString = "Prepare yourself to be caught
You in the hood gettin' shot
We going throw hell of blows
got my whole frame froze";
$myArray = explode(PHP_EOL, $myString);
print_r($myArray);
First of all, I think it's usually \r\n, second of all, those are not the same on all systems. That will only work on windows. It's kind-of annoying trying to figure out how to replace new lines because different systems treat them differently (see here). You might have better luck with just \n.
Losing line breaks from posting from input textboxes?
What works faster for me is to copy paste any text or Excel or HTML table type or newline type of data and paste it into a textarea instead of an inputextbox:
this keeps the linebreaks intact in the POST.
<textarea id="txtArea" name="txtArea" rows="40" cols="170"></textarea>
<br>
<input type="submit" value="split lines into array" />
in the form receiving file:
$txtArea ='';
$txtArea = $_POST['txtArea'];
$TA = $_POST['txtArea'];
$string = $TA;
$array = preg_split ('/$\R?^/m', $string);
// or any of these:
// $array = explode(PHP_EOL,$string);
// $array = explode("\n", $txtArea);
echo "<br>A0: ".$array[0];
echo "<br>A1: ".#$array[1];
echo "<br>A2: ".#$array[2];
Try this:
explode(PHP_EOF, $lines);
Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:
$skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
$skuList = str_replace("\\n\\r", "\n", $skuList);
$skuList = preg_split("/\n/", $skuList);
print_r($skuList);
This method always works for me:
$uniquepattern="##$;?:~#abcz"//Any set of characters which you dont expect to be present in user input $_POST['skuList'] better use atleast 32 charecters.
$skuList=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['skuList'])));

How to print line break in cakePHP?

How do you print a new line break in CakePHP.
I have tried this out:
echo "<b>\nhelloworld\n</b>";
instead of printing the it into three separate lines like this way:
<br>
helloworld
</b>
it just printed in this way when I viewed the HTML source code:
<b>helloworld</b>
Try \r\n instead of \n.
You could initially try just pressing enter and see if it's picked up...
If that doesn't work
Try doing it like this.
echo "<b>"."\n"."helloworld"."\n"."</b>";
that indeed is exactly how you add line breaks. What are you using to view the source code? Some tools, such as Firebug, normalise and reformat the source code for you which is why you might not be seeing the breaks.
You have to escape the backslash:
echo "<b>\\nhelloworld\\n</b>";
Your original line of code worked fine for me. I see that Anax solved your problem, above, but I wonder why carriage returns should be necessary but only in some circumstances?

Categories