繁体   English   中英

PHP-在div中从mysql文本字段显示html

[英]PHP - Displaying html from mysql text field in a div

从mysql数据库中的文本字段检索html标记后,我在显示html标记时遇到一些问题。

我的代码看起来像这样:

<div class='textDiv'><? echo htmlspecialchars_decode(str_replace("\r\n", "<br>", $row["textField"]), ENT_NOQUOTES);?></div>

因此,当mysql中的文本字段只有纯文本时,一切都很好,但是当我在文本内添加链接时,在链接标记之前和之后都会出现换行符,并且显示的文本变为以下行:

Some text justified over the div, then a sudden break
text with link to source
then the text continues justified as normal

但是,脚本生成的HTML代码如下所示:

<div class="textDiv">Senior Advisor said in a <a href="test.html">media interview</a> that the overall monetary policy tone is shifting towards...</div>

你们知道为什么会发生这种情况以及如何解决吗? 这样文本可以流畅显示而不会出现换行符?

当您使用htmlspecialchars_decode所有文本的html都将被解码,因此,如果要保留解码功能

1)将链接更改为普通链接的外观,例如:yourwebsite.com/test.html不要添加标签

2)不要直接回显字符串

$text = htmlspecialchars_decode(str_replace("\r\n", "<br>", $row["textField"]);

3)然后将变量$ text传递给代码以检测链接,这是一个:-

        $reg_exUrl = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.\,]*(\?\S+)?)?)*)@';
    if(preg_match($reg_exUrl, $text, $url)) {
    echo preg_replace($reg_exUrl, '<a href="https://'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
    } 
    else 
    {
    echo $text;
    }

您可以更改代码以适应您的需求

暂无
暂无

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

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