【发布时间】:2017-11-07 03:57:12
【问题描述】:
我有一个带有<br> 标签的文本,我想将它作为新行保存到 MySQL 数据库中。不是 HTML 标签。
例如:
$string = 'some text with<br>tags here.'
我想像这样将它保存到 MySQL 中:
some text with
tags here
str_replace 有什么权利用于此目的?谢谢。
【问题讨论】:
标签: php
我有一个带有<br> 标签的文本,我想将它作为新行保存到 MySQL 数据库中。不是 HTML 标签。
例如:
$string = 'some text with<br>tags here.'
我想像这样将它保存到 MySQL 中:
some text with
tags here
str_replace 有什么权利用于此目的?谢谢。
【问题讨论】:
标签: php
PHP 中已经有一个函数可以将新行转换为 br,称为nl2br()。然而,反过来是不正确的。相反,您可以像这样创建自己的函数:
function br2nl($string)
{
$breaks = array("<br />","<br>","<br/>");
return str_ireplace($breaks, "\r\n", $string);
}
那么,只要你想使用它,只要这样调用它:
$original_string = 'some text with<br>tags here.';
$good_string = br2nl($original_string);
有三点值得一提:
PHP_EOL 而不是 \r\n。无论您使用什么系统,这都会给出正确的换行符。<br /> 和其他变体。如果您需要考虑这些变化,那么您应该使用preg_replace() 函数。话虽如此,人们可能会过度思考所有可能的变化,但仍然无法将它们全部考虑在内。例如,考虑<br id="mybreak"> 以及许多其他属性和空白的组合。【讨论】:
您可以按照您的建议使用str_replace。
$string = 'some text with<br>tags here.';
$string = str_replace('<br>', "\r\n", $string);
虽然,如果您的 <br> 标签也可能被关闭,<br /> 或 <br/>,则可能值得考虑使用 preg_replace。
$string = 'some text with<br>tags here.';
$string = preg_replace('/<br(\s+\/)?>/', "\r\n", $string);
【讨论】:
来试试这个。这会将所有<br> 替换为\r\n。
$string = 'some text with<br>tags here.';
str_replace("<br>","\r\n",$string);
echo $string;
输出:
some text with
tags here.
【讨论】:
您可以使用htmlentities——将所有HTML字符转换为实体和html_entity_decode将HTML实体转换为字符
$string = 'some text with<br>tags here'
$a = htmlentities($string);
$b = html_entity_decode($a);
echo $a; // some text with<br>tags here
echo $b; // some text with<br>tags here
【讨论】:
试试看:
mysql_real_escape_string
function safe($value){
return mysql_real_escape_string($value);
}
【讨论】: