PHP: How to prevent unwanted line breaks - php

I'm using PHP to create some basic HTML. The tags are always the same, but the actual links/titles correspond to PHP variables:
$string = '<p style="..."><strong><i>'.$title[$i].'</i></strong>
<br>';
echo $string;
fwrite($outfile, $string);
The resultant html, both as echoed (when I view the page source) and in the simple txt file I'm writing to, reads as follows:
<p style="..."><a href="http://www.example.com
"><strong><i>Example Title
</i></strong></a></p>
<br>
While this works, it's not exactly what I want. It looks like PHP is adding a line break every time I interrupt the string to insert a variable. Is there a way to prevent this behavior?

Whilst it won't affect your HTML page at all with the line breaks (unless you are using pre or text-wrap: pre), you should be able to call trim() on those variables to remove newlines.
To find out if your variable has a newline at front or back, try this regex
var_dump(preg_match('/^\n|\n$/', $variable));
(I think you have to use single quotes so PHP doesn't turn your \n into a literal newline in the string).

My guess is your variables are to blame. You might try cleaning them up with trim: http://us2.php.net/trim.

The line breaks show up because of multi-byte encoding, I believe. Try:
$newstring = mb_substr($string_w_line_break,[start],[length],'UTF-8');
That worked for me when strange line breaks showed up after parsing html.

Related

Displaying html stored in a database with the appropriate line breaks

I have code written in a database in several languages, html, css, php, etc.
I want it to show on my page with the appropriate line breaks. Like this:
https://cdn.discordapp.com/attachments/668127780927701032/1016459728194375780/unknown.png
So, when I display html, it executes it instead of displaying it, which is normal.
So I use htmlspecialchar, except that I can't make a line break anymore, everything is displayed on one line. And I can't br out of this.
How do I do that?
Apparently your string contains literal \n characters, not newlines. So you need to replace that with <br>.
echo str_replace('\n', '<br>', htmlspecialchars($stmt['html']));

%0D%0A not creating a newline when echo is called

Every time I try to echo a string there is no new line. I how can I make a newline when calling echo in php using the $_GET?
here is my code:
<?php
$text = "Hello world";
$text2 = $_GET['msg'];
echo $text2
?>
and this is what I enter in the url:
http://localhost/hello.php?msg=hello%0Dworld
or this one:
http://localhost/hello.php?msg=hello%0Aworld
and even this one:
http://localhost/hello.php?msg=hello%0D%0Aworld
The echo has to be a newline please don't say I should use a different method than $_GET. It has to be $_GET
While performing your exercises you are creating an HTML page.
HTML is a special markup language, which renders according to set of rules, some of them are:
<> characters has a special meaning of control structures named tags
all newline characters are ignored
to make a newline on the page, one have to use suitable tag - such as <br>, <p> or whatever.
So, to make a newline appear on your page, you have to convert newline characters to tags. Either use nl2br() function to get a <br /> tag or str_replace() if you want any other one
Be aware that echoing any request variables without validating them is a considerable security risk! If you want to publish any application with this code it needs to be redesigned.
As common sense states, the conversion from urlencoded to the corresponding character is automatically done by php, but HTML does not render such characters, so you either need to convert them into linebreaks or enclose the message in <pre> tags.

How do i enable line breaks in php?

I am making a comments system in which i can accept user input with line breaks.
I don't want to show the \n or \r thing
Please help me with this
nl2br($string);
is fast and easy
They are enabled by default. If you are outputting the text to a web browser, make sure to use nl2br or the white-space attribute in CSS.
using preg_replace
simply replace it
preg_replace('/\n/'," ",$str);
\n should do the trick.
if you are trying to output a textarea, then use nl2br();
also:-
If you are trying to format your HTML source, you should use the constant PHP_EOL. The main reason being that on windows machines the EOL is \r\n and on UNIX machines it is \n. With a properly installed LAMP set up just use PHP_EOL like so.
$html.="<p>This is my HTML</p>" . PHP_EOL;
Line breaks will be stored just like any other character.
\n is an escape code that allows you to explicitly insert a line break into a string, but I don't think that it's relevant here.
The issue you're actually facing is that HTML does not impart any visual meaning to a line break. Line breaks within HTML code do not, under normal circumstances, equate to a line break on the screen.
One way to render a line break in HTML is to use a line break tag, or <br>.
In PHP, you can automatically convert line breaks to <br> with the nl2br function. Applying this to your comment text when you output it into HTML will enable you and other visitors to see the line break visually.

PHP Linefeeds (\n) Not Working

For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.
Example:
error_log('test\n', 3, 'error.log');
error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document
I'm pretty sure you are outputting to a html file.
The problem is html ignores newlines in source which means you have to replace the newlines with <br/> if you want a newline in the resulting page display.
You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');
to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);
It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.
Double quotes are what you want. Single quotes ignore the \ escape. Double quotes will also evaluate variable expressions for you.
Check this page in the php manual for more.
The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>
If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.

PHP form removing line breaks

I use a php form processor script that works fine. Except when users submit text in a multi-line text field, any line breaks or new lines are stripped out of the resulting string variable that is passed on. This often makes it unreadable by whoever receives the form results.
I'm no php expert but am sure the answer lies in the code that is stripping characters. What I'm unsure of is if I stop it stripping characters will this result in a security risk?
The strip array reads:
array('*', '|', '>', '<', '/', '\\\', '\"', 'Bcc', 'BCC', 'bcc');
What can I change here to retain the line breaks?
Thanks in advance for any help.
If your problem is with the submitted string then this means that the submitted string did not contain any line breaks or newline chars.
In one occassion i looked up the wrap="(hard|physical)" attribute on the text area. Some values of this attribute force the textarea to maintain line-breaks in the user text.
Did you try using nl2br($text) on the submitted text;
I believe you have an issue at the rendering phase. Have you tried:
echo nl2br($text);
Where $text is the text you're talking about.
Nothing there is stripping line breaks.
It's more likely that you're not doing anything on the display side to make the line breaks display. You're outputting HTML, and to HTML a line break is just more whitespace. You'll probably benefit from applying nl2br().

Categories