How to insert nl2br function with htmlspecialchars? I have a site where input is taken from textarea and nl2br is used to convert next line to a paragraph. When I tried with htmlspecialchars I got the below output. Here I wrote three 'test' words in textarea and saved in database. I am using htmlspecialchars to prevent html injections but because of this function nl2br function is not working. Can you tell be how to work around this problem?
test<br/>test<br/>test<br/>
yo do:
htmlspecialchars(nl2br($text));
you need:
nl2br(htmlspecialchars($text));
Call nl2br after you call htmlspecialchars:
echo nl2br(htmlspecialchars($the_text));
It's about using the right order,
htmlspecialchars(nl2br($string)); will produce the result you describe.
nl2br(htmlspecialchars($string)); will produce the result you wish.
nl2br
Inserts HTML line breaks before all newlines in a string
htmlspecialchars
Convert special characters to HTML entities
$text = "Hello \n World";
$unexpected_result = htmlspecialchars(nl2br($text)); // => "Hello <br /> World"
$expected_result = nl2br(htmlspecialchars($text)); // => "Hello <br/> World"
... That's why we need to use use htmlspecialchars before nl2br
Related
I try this:
echo nl2br($row['content']);
But what I get is:
Hello everybody\n Good luck!
Why doesn't it convert the \n? the database is storing data as UTF-8.
In addition, I check it with a test string, and found out that if the string is with double quotes it doesn't work too.. I mean:
echo nl2br("Hello everybody\n Good luck");
It should work but if you wish you can try str_replace("\n","<br />") instead of nl2br.
The issue is that the text is being stored with an additional slash in your database. Use the stripslashes (PHP doc here) function on the text before nl2br (PHP doc here)
$myText = "Hello\\nWorld"; //text from a database (with line breaks escaped)
stripslashes(nl2br($myText));
print $myText;
// Result: Hello<br>World
I guess you have written to database \n as two characters, so it's not a "new line" character.
Try echo str_replace('\n','<br />', $row['content'])
Currently, I'm using the following code:
preg_replace('/\s+/m','<br>',$var);
to replace line ends with <br> elements. An example of what I want:
Text Text Text
Text Text Text
Text Text Text
Should end up being:
Text Text Text<br>Text Text Text<br><br>Text Text Text
This does what it needs to, but I'd like to recognize when there is a double space and add two breaklines, instead of a single one. How can I do this, while retaining the current effect for single break lines?
I'm not too familiar with how preg_replace() works and I actually had to get help here to get that function in the first place. I took a look in the PHP manual and the function seemed a little confusing. Would anyone know of a site where I could learn how it works correctly?
You can simply replace each end-of-line character with <br />:
$var = str_replace(array("\r\n", "\n"), '<br />', $var);
There is no need to use a regular expression, but if you really want, you can use preg_replace to achieve the same effect:
$var = preg_replace("/\r?\n/", '<br />', $var);
you can do this by adding the g-modifier to the preg_replace like so:
preg_replace('/\s+/mg','<br>',$var);
preg stands for Perl Regular Expression - you'll find a lot more examples with this search string, e.g. this site or this site (I'm actually unsure, what the m-modifier does?)
Alternatively, you could use the simple $var = str_replace(' ', '<br', $var). I'm unsure, which one is faster.
Edit: If you want to replace newlines with html-breaks, use the nl2br() function.
php has a built in function for this
echo nl2br( $var );
this does \n, \r\n, \r, and \n\r
http://www.php.net/manual/en/function.nl2br.php
Check out this one. Not sure you are asking for that, but at least it works for me
$input = <<<DOC
Test Test Test
Test Test Test
Test Test Test
DOC;
$output = preg_replace("/$/m","<br/>",$input);
echo $output;
Hovewer, nl2br does just the same.
Is this what you’re trying to do?
<?php
$text = <<<EndText
Text Text Text
Text Text Text
Text Text Text
EndText;
$text = str_replace("\r", "", $text);
$text = str_replace("\n", "<br>", $text);
echo $text;
?>
I'm having some problems with a "bb parser" I'm coding. Or, well, not with the parser itself, but the nl2br modifying it.
The string from the database is like the following:
text text text
[code]code code code[/code]
text text text
Now, nl2br puts one br / after the first "text text text", and then another one below that, so there's two line breaks before the [code] tag (which actually is correct, but not what I want).
Is there any way I can limit how many br's are entered in a row? I can't seem to find a solution that's simple enough.
Thanks in advance, guys.
In addition to previous solution, I add a different one, since Fredrik asked for it. This will replace double <br> after nl2br instead of before.
$string = nl2br( $string );
$string = preg_replace( '/(<br(?: \\/)?>\\r?\\n?\\r?)(?=\\1)/is', '', $string );
You could for example replace two linebreaks (or more) by one by using preg_replace :-)
You could use
$string = str_replace(array("\r\n\r\n", "\n\r\n\r", "\n\n", "\r\r"), array("\r\n","\n\r","\n","\r"), $string);
This prevents double <br> tags. Preg_replace as suggested before is better if there could be more than two new lines in a row.
I have a textarea form in my html. If the user hits enter between 2 sentences that data should be carried over to my PHP.
Currently if the user enters:
Apple
Google
MS
and my PHP code is:
$str = $_POST["field"];
echo $str;
I get
Apple Google MS
as the output. I want output to be like this
Apple
Google
MS
what should I do?
Try nl2br() instead:
echo nl2br($str);
The newlines should be included in the string that you get from $_POST["field"]. However, if you then use that string as output in HTML, newlines will be treated as whitespace. To force the line breaks, use preg_replace("/\n/", "<br />", $str).
This is because when you echo it it's being displayed as HTML. A \n character is interpreted as a space. If you view the source you'll see your desired output.
To convert \n to <br> use:
echo nl2br( $str );
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.