Newline is not coming while echoing [duplicate] - php

This question already has answers here:
Why does the browser renders a newline as space?
(6 answers)
Closed 8 years ago.
I have started learning PHP. In my first code the newline is not coming properly. I have gone through the PHP doc, but still I'm not getting the problem.
<?php
# Echoing
echo "Hello World to PHP \n";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";
# Variable Basics
$name = "Vivek Kumar";
$age = 26;
echo "My name is $name and age is $age .";
echo 'My name is '. $name . ' and age is ' . $age . '.';
?>
output:
Hello World to PHP Concatenation in PHP is done using .Vivek
kumarLearning phpMy name is Vivek Kumar and age is 26 .My name is
Vivek Kumar and age is 26.

I assume you echo the output into a html page you look at with a web browser? In that case the linebreaks do get copied to the output, however they are not visualized as such. This simply is because in html markup a linebreak is something different to a plain text file.
Check about the use of <br> or <br /> linebreaks for such markup. Also php offers the handy nl2br() function for such purpose.
An example for such output (see it here):
Hello World to PHP Concatenation in PHP is done using .
<br />
Vivek kumarLearning phpMy name is Vivek Kumar and age is 26 .
<br />
My name is Vivek Kumar and age is 26.
But in general you should think about whether you really simply want to concatenate such strings when putting them in to html markup. Typically you want to wrap them in (invisible) containers like spans, divs or paragraphs, so that you can control the final layout by using styles (style sheets / css).
An arbitrary example (see it here)
HTML:
<div id="intro">Hello World to PHP Concatenation in PHP is done using .</div>
<h2>Vivek kumarLearning php</h2>
<div class="plain">My name is Vivek Kumar and age is 26 .</div>
<div class="plain">My name is Vivek Kumar and age is 26.</div>
CSS:
body {
font-size: 130%;
}
#intro {
font-weight: bold;
margin-bottom: 10px;
}
.plain {
font-size: 100%;
}

You can use nl2br to convert new line (\n) to line break (<br>).
From http://php.net/manual/en/function.nl2br.php:
string nl2br ( string $string [, bool $is_xhtml = true ] )
Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).
Or you can just use line break, as the others have suggested. nl2br is handy when showing text from a form text area.

if you are using this in a browser you should use <br> tag or you should use <pre>
I am posting the answer with <pre> and with <br>
**with `<pre>`**
<?php
# Echoing
echo '<pre>';
echo "Hello World to PHP "."\n";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";
echo '<pre>';
with
echo "Hello World to PHP "."<br/>";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";

Related

PHP doesn't show line break in textarea value in echo

I am creating a post_blog.php file where user will enter all fields one by one like post_title, post_author etc.
When user write post_text which contains many paragraphs and i get that text by using post method in php it displays me all value in plain text . it do not contain any paragraphs etc.
Here is the code :
<textarea rows="400" cols="100" name="post_text">
Enter post text here .. upto 5000 characters .
</textarea>
in php :
if()....
echo $post_text = $_POST['post_text'];
Demo Input in post_text:
Enter post text here
.. upto
5000
characters .
OUTPUT:
Enter post text here .. upto 5000 characters .
Expected OUTPUT :
Enter post text here
.. upto
5000
characters .
Your problem isn't in the php; Your problem is that HTML doesn't accept white spaces (line breaks, sapces, etc.) and display them as one space. There are some solutions:
Use the <pre> tag, which shows the text as-is:
<?php
...
echo '<pre>' . $post_text = $_POST['post_text'] . '</pre>';
Use the CSS white-space: pre; definition, which is excatly like the <pre> tag, except that it's can be applied to any element, and you cannot style a <pre> tag:
<?php
...
echo '<div style="white-space: pre;">' . $post_text = $_POST['post_text'] . '</div>';
See MDN Docs about CSS' white-space declaration.
The last solution is to replace any line break with the <br> tag and any space with :
<?php
...
echo $post_text = str_replace(' ', ' ', str_replace('\n', '<br>', $_POST['post_text']));
When user press Enter, line break \n inserted in string but in html doesn't show. You should convert it to <br> to showing in html. The str_replace() can replace it in string.
$newStr = str_replace("\n", "<br>", $str)
Also you can use native function nl2br() that inserts HTML line breaks before all newlines in string as #VictorFedorenko mentioned in comment
$newStr = nl2br($str)

php print statements in separate lines

The following php script prints several statements and variables! they print on the sameline! i want to print them in separate lines one after the other! How can i do it?
for example the 1st 2 statements should be printed as:
Programming in PHP is fun
I learnt how to comment in PHP
but currently it prints as
Programming in PHP is fun I learnt how to comment in PHP
?php
echo "Programming in PHP is fun";
//This is the 1st programming 4 tutorial
/*This tutorial helped me
to gain a good knowledge in php! */
print "I learnt how to comment in PHP";
echo "A variable name must start with a letter or an underscore '_' -- not a number";
echo "A variable name can only contain alpha-numeric characters, underscores (a-z, A-Z, 0-9, and _ )";
echo "A variable name should not contain spaces. If a variable name is more than one word, it should beseparated with an underscore or with capitalization ";
$name= "My name is XXX";
$number=25;
$float_number=10.245;
$negative_number=-12;
echo($name);
echo($number);
echo($float_number);
echo($negative_number);
$age=24;
$feature =$age;
echo($feature);
$x=45;
$y=12;
echo($x+$y);
$myName="My name is 'Lasith'";
?>
If you echo them as plain text, add a newline character after each echo:
echo "\n";
If you echo them to HTML (into a web browser), add a HTML <br> tag after each echo:
echo "<br>";
You can also use string concatenation
echo "Programming in PHP is fun" . "\n";
echo "Programming in PHP is fun" . "<br>";
or add the newline or <br> tag to the string
echo "Programming in PHP is fun\n";
echo "Programming in PHP is fun<br>";

Replace pattern between several string delimiters in PHP - Use of backreferences [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 6 years ago.
I have the following string in PHP:
$string = "<img src=\"url\" >HELLO WORLD<ol>I must replace the text after img and before ol.</ol>";
print htmlentities($string);
I want to find the substring HELLO WORLD (or whatever substring is, that is just an example of a text that will be completely dynamical), using the delimiters : "<img ... >" and "<ol>" and add <h3> delimiters. So the string above would result in:
<img src="url" ><h3>HELLO WORLD</h3><ol>I must replace the text after img and before ol.</ol>
I have tried the following code, of course with no success:
$string = preg_replace("/\<img (.*?)\> (.*?)\<ol\>/", "<img (.*?)><h3> (.*?)</h3></ol>", $string);
I know how to make very easy substituions, but the above condition is very far from my understanding.
I have found the answer by trial-and-error:
$string = "<img src=\"url\" >HELLO WORLD<ol>I must find the text after img and before ol.</ol>";
$string2 = preg_replace("/<img (.*?)>(.*?)<ol>/", "<img $1><h3>$2</h3><ol>", $string);
print htmlentities($string) . " <br />" . htmlentities($string2);
Explanation: I add the delimiters, and use $1 and $2 for matching the results between the delimiters in the right order.

text-indent on user formatted text

I would like to use the text-indent property (or something like this) to add a indentation of the first line of each paragraph.
First the user can write his text in a textarea, then save it in a DB.
When I want to display this text i use :
$exhib = $res->fetch_array();
echo "<div class='infoContent'>". nl2br($exhib['description']) . "</p></div>";
The line return of the user are stored as \n in DB, and modified to <br /> by nl2br. With my CSS :
.infoContent
{
text-indent: 10px;
}
only the first line is indented. (normal behavior).
Q : How can I make this indentation automatic for each line after a <br /> tag ?
I tried a ugly solution, but it doesn't work because empty paragraph section <p></p> doesn't create another line return (in case the user enter 2 line return \n\n).
echo "<div class='infoContent'><p>" . str_replace("<br />", "</p><p>", nl2br($exhib['description'])) . "</p></div>";
I can replace <p></p> tag by <br /> but it seems to be a very bad solution...
EDIT:
JSfiddle
Thanks
\n\n usually means a new paragraph (enter). The white space between paragraphs is CSS and is actually default browser styling (1em I think?). \n is a <br> (shift + enter).
So don't use nl2br() and do it yourself:
$text = '<p>' . htmlspecialchars($text) . '</p>'; // HTML ENCODE!
$text = preg_replace('#\n\n\n*#', '</p><p>', $text); // 2 or more \n
$text = preg_replace('#\n#', '<br />', $text); // all left-over \n
$text = preg_replace('#><#', ">\n<", $text); // if you like </p>\n<p> with a newline between, like I do
http://3v4l.org/b0AhL
This is pretty much what Markdown does (and Textile and those): 1 newline = BR (not exactly in Markdown) and 2 newlines = P. I always use simple Markdown for rendering plain text.
When you submit your textarea, instead of using CSS to indent only the first line, you can use (non-breaking space).
when you submit your text area, I assume you grab it as such:
$userText = $_POST['description']
Well, before you submit to your database, you could use a simple replace - After you grab the text:
$userText = str_replace("\n", "\n ", $userText);
Then submit that to the database. When it comes back, the nl2br will still make the \n into a <br /> and then it won't see the , though the HTML will see them as four spaces (equal to an indent).
It's dirty, but simple!
Reference: http://www.w3schools.com/php/func_string_str_replace.asp

How to break a text into the next line in php?

i have this project which is blog type where I pull posts submitted from the server. The problem is that when the post is echo(ed) the text goes all in one line , how do I make it go to the next line after certain length?
Here is the code where the text is being posted
$postpost = $result["post_user"];
echo " <b>name</b> = " .$result["username"] ."<br>";
echo " <b>post</b> = " .$result["post"] . "<br>";
echo " <b>date</b> = ".$date["date"]. "
<br><br>----------------------<br><br>";
and here is the output problem
Use wordwrap() :
// the 80 is the number of characters after which to break:
echo " <b>post</b> = " . wordwrap($result["post"], 80, '<br>') . '<br>';
You may also be interested in nl2br().
$postpost = $result["post_user"];
echo " <b>name</b> = " .$result["username"] ."<br>";
echo " <b>post</b> = " .chunk_split($result["post"],100,"<br/>") . "<br>";
echo " <b>date</b> = ".$date["date"]. "
<br><br>----------------------<br><br>";
This will break it after 100 characters. You can change the 100 to your needs.
But wordwrap is a better solution :)
You can use wordwrap function in php
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
?>
echo implode('<br/>',str_split($string,100));
Firstly, if you want the text to have a maximum width, enclose the whole thing in a wrapping <div> element, and use CSS to style it to a maximum width. Any text inside the element with then wrap nicely.
Here's the CSS code you'd need:
#mydiv {width:200px;}
The only text that will still be a problem after that is text without any spaces in it, which would still stretch off the edge of the page.
For these, you can use another CSS property, word-wrap, like so:
#mydiv {word-wrap:break-word;}
The best practice is to keep your CSS code separate from your HTML, but if you're not using stylesheets, you can add the CSS code directly to the <div> element with the style attribute, like so:
<div style='width:200px; word-wrap:break-word;'>
..... (your content goes here) .....
</div>
It is, of course, possible to do word-wrapping in PHP, using it's wordwrap() function (or str_split() for long strings with no spaces), but you'll end up with the lines being varying lengths when displayed on the page, because the font has different widths for different characters. Therefore, I would say that the CSS solution is better because the word wrapping will look better on the page.
Hope that helps.
this should do it :
$newtext = wordwrap($text, 20, "<br />\n");
examples can be found here
Use php's wordwrap() function.
http://php.net/manual/en/function.wordwrap.php
Edit: I initially thought this is a CSS problem. I see that you want to break strings which are very large with php. You can use wordwrap() for that, as artlung recommended.
What I initially thought in CSS: put each blog entry into a div, and assign word-wrap: break-word; for the div and also specify width of the div.
My idea on jsfiddle.com: Link

Categories