PHP - Split string containing newline and print - php

Why is the following code not working...?
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
It prints
hello world !
Instead of
hello
world
!
Thanks

You also have to echo <br />
The HTML <br /> element produces a line break in text (carriage-return).
It is useful for writing a poem or an address, where the division of
lines is significant.
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
echo "<br />";
}
doc: <br />
Another option is to use nl2br to inserts HTML line breaks before all newlines in a string
$test = "hello \n world \n !";
echo nl2br($test);
Doc: nl2br()

Add new line to Browser Output via HTML
In HTML, you need to add line break for new line via HTML Tag. This will not appear as required output if there is line break in text/string.
<br> used to add single line break.
Replace
echo $line;
Into
echo $line."<br>";
Add new line to string/source code
If you need to add new line into source code only then replace echo $line; with echo $line."\n";
\n is used into double quotes for new line.
Add new line to Browser Output via PHP
Anyways an other way to do this via PHP is to use PHP's built-in method nl2br()

$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
The result is:
hello world !
Basically you have split on the newlines, and the newlines are not included as you print out each split part.

Use nl2br($line) and replace the delimiter with empty space.This way your new line will be visible in html:
$test = "hello \n world \n !";
foreach(explode(" ",$test) as $line){
echo nl2br($line);
}
will output:
hello
world
!
and the output html:
hello<br />
world<br />
!

Related

How to insert a new line break within the php code

<?php echo nl2br($valueu->getarea($rows['province'].'|'.$rows['city'].'|'.$rows['area'],' ')); ?></td>
how to put a line break in between city and area when outputted to a browser.
Thanks
Use \n. Just add it with the sting like this I."\n" like pie.
You can also use nl2br like this echo nl2br("One line.\nAnother line.");
Try double quote "\n".
If you use single quote '\n', PHP will just interpret as a literal \n, but within double quote, it will parse it as an escape sequence (newline character) and echo it. More about strings here.
echo nl2br('Hello \n world');
// -> Hello \n world
echo nl2br("Hello \n world");
// -> Hello <br /> world
In a browser, you may need to use "<br/>" instead of a newline "\n".
echo($valueu->getarea($rows['province'].'|'.$rows['city'].'<br />'.$rows['area'],' '));
Something like that?

How to escape backslashes in files

I am trying to work on a script but I am stuck in one place.
Eg. To get a php output I have used..
str_php = """
<?php
echo "Hello World!";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
Ok, so I get the output as it is....
<?php
echo "Hello World!";
?>
So my php code is running. all good till here. But, the problem starts from when I try using "\" and "\n" and "\r"
str_php = """
<?php
echo "Hello World!"; \n echo "How are you"; \n echo "God bless you";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
But here I dont get the output as it is.
<?php
echo "Hello World!";
echo "How are you";
echo "God bless you";
?>
And the "\" it just vanishes... at an output.
Eg. I want an output of a php hyperlink something like...
str_php = """<?php
print("$dirArray[$index]");
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
and the output I get is...
<?php
print("$dirArray[$index]");
?>
The "\" is missing and the php does not run creating error.
print("$dirArray[$index]") - Original
print("$dirArray[$index]") - python output
Can any one help me out with "\", "\n", "\r" ??
Just use "\" to escape the "\" character.
Since it is common to want to have long strings containing several "\", Python also allows one
to prefix the string opening quotes if ar r (for "raw") - inside such
a string, no escaping of "\n" to chr(10) or "\t" to chr(9) happens:
>>> print (r"Hello \n world!")
Hello \n world!
You need to escape your "\" with another backslash writting it as "\\".
If you use "\n" it will be parsed and make a newline. Try to use '\n', strings enclosed in '\n' are not parsed and it should print out as you want it to.

php Newlines vs html break

This code:
<?php
echo "This is the first line. \n";
echo "This is the second line.";
?>
Echoes out all on the same line: ("This is the first line. This is the second line.")
Shouldn't \n have basically the same function as <br> ? What am I missing here?
HTML doesn't render \n, a \n will put a break in your HTML source code
PHP
<?php
echo "<p>This is the first line. \n";
echo "This is the second line.</p>";
?>
HTML Source
<p> This is the first line.
This is the second line.</p>
HTML
This is the first line. This is the second line.
PHP
<?php
echo "<p>This is the first line.";
echo "This is the second line.</p>";
?>
HTML Source
<p> This is the first line.This is the second line.</p>
HTML
This is the first line.This is the second line.
PHP
<?php
echo "<p>This is the first line. <br/>";
echo "This is the second line.</p>";
?>
HTML Source
<p> This is the first line.<br/>This is the second line.</p>
HTML
This is the first line.
This is the second line.
You mix up the output of php and the result in your browser. \n is newline. You may see it, when you read the source code in your browser(Ctrl + U in Chrome) .
But browser only render <br> as newline on webpage
echo "This is the first line. \n";
Will produce a linebreak in your source, meaning the cursor is currently on the next line (the line belove the text).
echo "This is the second line.";
Will produce a single line and leave the cursor right after the text (on the same line).
echo "This is the second line.<br />";
Will produce a single line but in rendered html containing a visible linebreak. However, in the sourcecode there will be no linebreaks, so:
echo "Line one<br />Line two";
Will render two lines in html but one line in the source.
echo "This is the first line.", '<br />', PHP_EOL;
^ HTML code for BR and ENTER.ENTER is visible in the source or PRE tags, or TEXTAREAs, or when enabled by CSS white-space (etc.) while BR is the line break in HTML.

Line breaks from textarea and mysql dont appear in html

How can I make text appear on diff lines in html?! They appear on diff lines in my text area when output from mysql, and also appear on diff lines inside mysql. But in the web page its all on one line. How can this be solved?
Use:
string nl2br ( string $string [, bool $is_xhtml = true ] )
It can handle \n, \r, \r\n or \n\r linebreaks and replaces them with a <br />
Example:
$yourText = "This is line one.\nThis is line two.";
$yourText = nl2br($yourText);
echo $yourText;
This will result in:
This is line one.<br />This is line two.
Link to the manual for more information.
Use the PHP nl2br function:
$string = "hello \n world";
$string = nl2br($string);
It's quite self-explanitory: \n gets replaced with <br />
Replace Linebreaks with <br>
str_replace(.N, '<br>', [element]);
You can use <pre>..Your text..</pre> tag for that.

Replace newlines with br but ignore newlines after h1 in PHP

Is it possible to replace newlines with the <br> tag, but to ignore newlines that follow a </h1> tag?
So for example I want to change this block:
<h1>Test</h1> \n some test here \n and here
To this:
<h1>Test</h1> some test here <br /> and here
$subject = "<h1>hithere</h1>\nbut this other\nnewline should be replaced.";
$new = preg_replace("/(?<!h1\>)\n/","<br/>",$subject);
echo $new;
// results in:
// <h1>hithere</h1>
// but this other<br/>newline should be replaced.
Should work. This says \n not preceeded immediately by h1>
Using string functions instead of regular expressions, and assuming the </h1> tag can be anywhere on the line (instead of just before the newline):
$lines=file($fn);
foreach ($lines as $line) {
if (stristr("$line", "</h1>") == FALSE) {
$line = str_replace("\n", "<br />", $line);
}
echo $line;
}
which, for your example, results in:
<h1>Test</h1>
some test here <br />and here<br />

Categories