Reputation: 271
I hope you can help you as you always do, thanks.
I have a form to input information in a textarea, I let the users write html tags because sometimes they would want to literaly write the html tags, so if they write something like this as input:
<h1>This is the input content</h1>
I like Pizza
I like Cheese
This is the end of the input, as you see I pressed enter several times
I save the input using nl2br, something like this:
$textForDataBase = nl2br($_POST['input']);
Then the database value is something like this:
<h1>This is the input content</h1>
I like Pizza<br />I like Cheese<br />This is the end of the input, as you see I pressed enter several times
Then before displaying the content I apply htmlspecialchars
to my string but I want that all html tags that's not a break line to be converted to html entities, So I tried to use preg_replace but i had no luck, What can I do?
$html = htmlspecialchars($val['descripcion']);
echo preg_replace('#<br\s*/?>#i', "\n", $html);
If I don't use htmlspecialchars the output would be something like:
But if I use it:
<h1>This is the input content</h1>
I like Pizza<br />I like Cheese<br />This is the end of the input, as you see I pressed enter several times
The expected output would be:
<h1>This is the input content</h1>
I like Pizza
I like Cheese
This is the end of the input, as you see I pressed enter several times
Upvotes: 0
Views: 1088
Reputation: 543
when u store input detail in db remove nl2br and store user detail as same as like input value and then when u display value first use htmlspecialchars and then use nl2br and finally echo it.
just change like this.
$textForDataBase = $_POST['input'];
$html = htmlspecialchars($val['descripcion']);
echo nl2br($html);
Upvotes: 1
Reputation: 964
Perhaps you could use strip_tags();
<?php
$string = "
<p>This is a p element</p><a href=''>An a element</a><h1>This is the input content</h1> I like Pizza<br />I like Cheese<br />This is the end of the input, as you see I pressed enter several times";
$output = strip_tags($string,"<br>");
echo $output;
Upvotes: 0