2017-07-11 31 views
0

我希望您能像往常一样帮助您,谢谢。如何在应用htmlspecialchars后替换html换行符

我有一个表格在一个文本输入的信息,我让用户写html标签,因为有时他们会想literaly写html标签,因此,如果他们写这样的事情作为输入:

<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 

我节省使用nl2br输入,这样的事情:

$textForDataBase = nl2br($_POST['input']); 

那么数据库值是这样的:

<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 

然后,在显示内容之前,我将htmlspecialchars应用于我的字符串,但我希望所有不是断行的html标记都转换为html实体,所以我尝试使用preg_replace,但我没有运气,我该怎么办?

$html = htmlspecialchars($val['descripcion']); 
echo preg_replace('#<br\s*/?>#i', "\n", $html); 

如果我不使用用htmlspecialchars输出会是这样的:

这是输入内容

我喜欢比萨
我喜欢奶酪
这是输入的结束,正如你看到的我按下Enter键数次

但是,如果使用它:

<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 

预期输出为:

<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 
+0

看看这个https://stackoverflow.com/questions/4114308/htmlentities-with-exceptions –

+0

,阻止改写(munging)输入。 –

+0

当你在db中存储输入细节时,移除nl2br并将用户细节存储为与输入值相同,然后当你显示值时首先使用htmlspecialchars,然后使用nl2br并最终回显它。 –

回答

1

当u储存到DB删除nl2br并存储用户详细地相同的输入细节像输入值,然后当U显示值第一次使用的htmlspecialchars,然后使用nl2br并最终回声它。

只是这样改变。

$textForDataBase = $_POST['input']; 

$html = htmlspecialchars($val['descripcion']); 
echo nl2br($html); 
+0

伟大的这是做的很快,正是我所需要的,非常感谢你! –

+0

不认为它会允许H1。 –

+0

这是目标,h1显示为我想要的纯文本。 –

0

也许你可以使用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; 
+0

嘿海德尔,感谢您的回答我没有测试它,因为Mahipal答案为我工作,但无论如何感谢! –