简体   繁体   English

换行符问题(NL2BR)

[英]Problems with newlines (nl2br)

My code works as follows: 我的代码如下:

  • Text comes to server (from textarea) 文本到达服务器(来自textarea)
  • Text is ran through trim() then nl2br 文本先通过trim()然后再运行nl2br

But what is happening is it is adding a <br> but not removing the new line so 但是发生的事情是它添加了<br>但没有删除新行,因此

"

something"

becomes 变成

"<br>

something"

which adds a double new line. 这增加了一个新的双行。 Please help this error is ruining all formatting, I can give more code on request. 请帮助此错误破坏所有格式,我可以根据要求提供更多代码。

Creation of post: Shortened creation method (Only showing relevent bits) Creation method: 创建帖子:缩短创建方法(仅显示相关事件位)创建方法:

BlogPost::Create(ParseStr($_POST['Content']));

ParseStr runs: ParseStr运行:

return nl2br(trim($Str));

Viewing of post: 查看帖子:

echo "<span id='Content'>".BlogPosts::ParseBB(trim($StoredPost->Content))."</span>";

ParseBB runs: ParseBB运行:

    $AllowedTags = array(
    //  i => Tag, Tag Replacement, Closing tag
        0 => array("code","pre class='prettyprint'",true),
        1 => array("center","span style='text-align:center;'",true),
        2 => array("left","span style='text-align:right;'",true),
        3 => array("right","span style='text-align:left;'",true)
    );
    $AllowedTagsStr = "<p><a><br><br/><b><i><u><img><h1><h2><h3><pre><hr><iframe><code><ul><li>";
    $ParsedStr = $Str;

    foreach($AllowedTags as $Tag)
    {
        $ParsedStr = str_replace("<".$Tag[0].">","<".$Tag[1].">",$ParsedStr);
        if($Tag[2])
            $ParsedStr = str_replace("</".$Tag[0].">","</".$Tag[1].">",$ParsedStr);
    }


    return strip_tags($ParsedStr,$AllowedTagsStr);

Example: What I see: 示例:我所看到的: What is shown: 显示内容:

Aren't you using UTF-8 charset? 您不使用UTF-8字符集吗? If you are using multibyte character set (ie UTF-8), trim will not work well. 如果您使用的是多字节字符集(即UTF-8),则修整将无法正常进行。 You must use multibyte functions. 您必须使用多字节函数。 Try something like this one: http://www.php.net/manual/en/ref.mbstring.php#102141 尝试类似这样的方法: http : //www.php.net/manual/zh/ref.mbstring.php#102141

Inside <pre> you should not need to call nl2br function to display break lines. <pre>内部,您无需调用nl2br函数即可显示折线。

Check if you really want to call nl2br when you are creating post. 创建帖子时,检查您是否真的要调用nl2br。 You probably need it only on displaying it. 您可能只在显示它时才需要它。

It's because nl2br() doesn't remove new lines at all. 这是因为nl2br()根本不会删除新行。

Returns string with <br /> or <br> inserted before all newlines ( \\r\\n , \\n\\r , \\n and \\r ). 返回所有换行符( \\r\\n\\n\\r\\n\\r之前插入 <br /><br>字符串。

Use str_replace instead: 使用str_replace代替:

$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM