将换行符转换为HTML break(<br>
)
什么是清洁剂?
str_replace(array("\r\n", "[br]", "\r"), '<br>', $Content);
OR
str_replace("\r\n", '<br>', $Content);
str_replace("[br]", '<br>', $Content);
str_replace("\r", '<br>', $Content);
我一直在使用第一种方法,但我的一位朋友说我目前使用的方式在处理方面更加草率。
我正在使用函数中的格式;所以
function Formatting ($Content)
{
$Content = str_replace(array("\r\n", "[br]", "\r"), '<br>', $Content);
return $Content;
}
答案 0 :(得分:1)
我会自己调整一下(来自手册页http://php.net/manual/en/function.nl2br.php中的用户注释:
<?php
/**
* Converts newlines and break tags to an
* arbitrary string selected by the user,
* defaults to PHP_EOL.
*
* In the case where a break tag is followed by
* any amount of whitespace, including \r and \n,
* the tag and the whitespace will be converted
* to a single instance of the line break argument.
*
* @author Matthew Kastor
* @param string $string
* string in which newlines and break tags will be replaced
* @param string $line_break
* replacement string for newlines and break tags
* @return string
* Returns the original string with newlines and break tags
* converted
*/
function convert_line_breaks($string, $line_break=PHP_EOL) {
$patterns = array(
"/(<br>|<br \/>|<br\/>)\s*/i",
"/(\r\n|\r|\n)/"
);
$replacements = array(
PHP_EOL,
$line_break
);
$string = preg_replace($patterns, $replacements, $string);
return $string;
}
?>
答案 1 :(得分:0)
在回应Dagons评论时,他的建议完美无缺;无需使用nl2br()
创建新功能来执行此任务