nl2br for paragraphs - php

$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
How do I convert each new line to paragraph?
$variable should become:
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>

Try this:
$variable = str_replace("\n", "</p>\n<p>", '<p>'.$variable.'</p>');

The following should do the trick :
$variable = '<p>' . str_replace("\n", "</p><p>", $variable) . '</p>';

Be careful, with the other proposals, some line breaks are not catch.
This function works on Windows, Linux or MacOS :
function nl2p($txt){
return str_replace(["\r\n", "\n\r", "\n", "\r"], '</p><p>', '<p>' . $txt . '</p>');
}

$array = explode("\n", $variable);
$newVariable = '<p>'.implode('</p><p>', $array).'</p>'

<?php
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$prep0 = str_replace(array("\r\n" , "\n\r") , "\n" , $variable);
$prep1 = str_replace("\r" , "\n" , $prep0);
$prep2 = preg_replace(array('/\n\s+/' , '/\s+\n/') , "\n" , trim($prep1));
$result = '<p>'.str_replace("\n", "</p>\n<p>", $prep2).'</p>';
echo $result;
/*
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
*/
?>
Explanation:
$prep0 and $prep1: Make sure each line ends with \n.
$prep2: Remove redundant whitespace. Keep linebreaks.
$result: Add p tags.
If you don't include $prep0, $prep1 and $prep2, $result will look like this:
<p>Afrikaans
</p>
<p>Shqip - Albanian
</p>
<p>Euskara - Basque</p>
Not very nice, I think.
Also, don't use preg_replace unless you have to. In most cases, str_replace is faster (at least according to my experience). See the comments below for more information.

Try:
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$result = preg_replace("/\r\n/", "<p>$1</p>", $variable);
echo $result;

I know this is a very old thread, but I want to highlight, that suggested solutions can have some issues in HTML world:
They do not check whether there is already a p tag around respective paragraph. This can result in extra paragraphs. At least some browsers will then show this as extra paragraphs, meaning <p>line1<p>line2</p>line3</p> will result in 3 paragraphs, which may not be the intention.
In fact, there is a bunch of tags, that are not expected inside of p, as per the spec of phrasing content. Or rather there is a limited set of tags, tha can be.
They will change new lines inside tags, where you want to preserve new lines as is. pre and textarea are the ones, where you could generally want that. code, samp, kbd and var are an example of other common values, but technically it can be any tag with white-space CSS property set to either pre, pre-wrap, pre-line or break-spaces.
They usually only check for \r\n or just \r or \n, while there are actually more symbols, that would mean new line, and they also have respective HTML entities, which can easily occur in HTML string.
To "combat" these flaws, at least, to an extent, I've just released a nl2tag library, which can also "convert" new lines to <li> items and has an "improved" nl2br logic (mostly for the sake of whitespace retention).
It's far from perfect (check the readme for limitations), but should cover you in case of relatively simple HTML string.

Related

str_ireplace or preg_replace replaced break tag into \r\n

I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

add newlines or line breaks after p closing tag with php

I have this text in a MySql database:
First paragraph very long.
Second paragraph very long.
Third paragraph.
I add p tags and it works:
$text = preg_replace("/\n/","<p>",$text);
$text = '<p>'.$text;
I try to add line breaks when I echo to a html page. I tried 3 different things. But none of them seem to work:
$text = preg_replace("/<\/p>/","</p>\n\n",$text);
$text = preg_replace("/<\/p>/","</p><br><br>",$text);
$text = nl2br($text);
echo $text;
If I go to the web inspector in the Safari browser, I get this:
<p>First paragraph very long.</p><p>Second paragraph very long.</p><p>Third paragraph.</p>
I would like to have this:
<p>First paragraph very long.</p>\n>\n
<p>Second paragraph very long.</p>\n>\n
<p>Third paragraph.</p>\n>\n
It seems that my regex does not select <\/p> even when I escape it. I do not understand. What is wrong?
Presuming you need newline control chars (and not html line break tags):
$text = "First paragraph very long.\nSecond paragraph very long.\nThird paragraph.";
$text = '<p>' . preg_replace("~\n~", "<p>\n\n</p>", trim($text)) . '</p>;
Note trim is used incase you have leading or trailing newlines, ~ is used as a delimiter, because / is a poor choice when dealing with html, causeing you to escape all over the place.
It is not apparent in the above example, but using some of your reqex as an example:
preg_replace("~</p>~","</p>\n\n",$text);
is much easier to read than:
preg_replace("/<\/p>/","</p>\n\n",$text);
Also, you dont need regex, you could just use str_replace:
$text = '<p>' .str_replace("\n", "<p>\n\n</p>", trim($text)) . '</p>;
Or even explode/implode:
$text = '<p>' . implode("</p>\n\n<p>", explode("\n", trim($text))) . '</p>';
If it was html line breaks you wanted, then you could just edit the replacement argument to:
"</p><br><br><p>"
in any of the above, but it would probably be better to use some css:
p{
margin-bottom:10px;
}
You don't need regex, simple str_replace works (in your example):
$text = str_replace( "</p><p>","</p>\n<p>",$text );

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

Keep all html whitespaces in php mysql

i want to know how to keep all whitespaces of a text area in php (for send to database), and then echo then back later. I want to do it like stackoverflow does, for codes, which is the best approach?
For now i using this:
$text = str_replace(' ', '&nbs p;', $text);
It keeps the ' ' whitespaces but i won't have tested it with mysql_real_escape and other "inject prevent" methods together.
For better understanding, i want to echo later from db something like:
function jack(){
var x = "blablabla";
}
Thanks for your time.
Code Blocks
If you're trying to just recreate code blocks like:
function test($param){
return TRUE;
}
Then you should be using <pre></pre> tags in your html:
<pre>
function test($param){
return TRUE;
}
</pre>
As plain html will only show one space even if multiple spaces/newlines/tabs are present. Inside of pre tags spaces will be shown as is.
At the moment your html will look something like this:
function test($param){
return TRUE;
}
Which I would suggest isn't desirable...
Escaping
When you use mysql_real_escape you will convert newlines to plain text \n or \r\n. This means that your code would output something like:
function test($param){\n return TRUE;\n}
OR
<pre>function test($param){\n return TRUE;\n}</pre>
To get around this you have to replace the \n or \r\n strings to newline characters.
Assuming that you're going to use pre tags:
echo preg_replace('#(\\\r\\\n|\\\n)#', "\n", $escapedString);
If you want to switch to html line breaks instead you'd have to switch "\n" to <br />. If this were the case you'd also want to switch out space characters with - I suggest using the pre tags.
try this, works excellently
$string = nl2br(str_replace(" ", " ", $string));
echo "$string";

Problems with newlines (nl2br)

My code works as follows:
Text comes to server (from textarea)
Text is ran through trim() then nl2br
But what is happening is it is adding a <br> but not removing the new line so
"
something"
becomes
"<br>
something"
which adds a double new line. Please help this error is ruining all formatting, I can give more code on request.
Creation of post:
Shortened creation method (Only showing relevent bits) Creation method:
BlogPost::Create(ParseStr($_POST['Content']));
ParseStr runs:
return nl2br(trim($Str));
Viewing of post:
echo "<span id='Content'>".BlogPosts::ParseBB(trim($StoredPost->Content))."</span>";
ParseBB runs:
$AllowedTags = array(
// i => Tag, Tag Replacement, Closing tag
0 => array("code","pre class='prettyprint'",true),
1 => array("center","span style='text-align:center;'",true),
2 => array("left","span style='text-align:right;'",true),
3 => array("right","span style='text-align:left;'",true)
);
$AllowedTagsStr = "<p><a><br><br/><b><i><u><img><h1><h2><h3><pre><hr><iframe><code><ul><li>";
$ParsedStr = $Str;
foreach($AllowedTags as $Tag)
{
$ParsedStr = str_replace("<".$Tag[0].">","<".$Tag[1].">",$ParsedStr);
if($Tag[2])
$ParsedStr = str_replace("</".$Tag[0].">","</".$Tag[1].">",$ParsedStr);
}
return strip_tags($ParsedStr,$AllowedTagsStr);
Example:
What I see:
What is shown:
It's because nl2br() doesn't remove new lines at all.
Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).
Use str_replace instead:
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
Aren't you using UTF-8 charset? If you are using multibyte character set (ie UTF-8), trim will not work well. You must use multibyte functions. Try something like this one: http://www.php.net/manual/en/ref.mbstring.php#102141
Inside <pre> you should not need to call nl2br function to display break lines.
Check if you really want to call nl2br when you are creating post. You probably need it only on displaying it.

Categories