【问题标题】:PHP - Displaying html from mysql text field in a divPHP - 从 div 中的 mysql 文本字段显示 html
【发布时间】:2017-06-05 19:07:58
【问题描述】:

从我的 mysql 数据库中的文本字段中检索到 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>

你们知道为什么会发生这种情况以及如何解决吗?让文字显示流畅不换行?

【问题讨论】:

  • 您必须对 CSS 文件或代码进行一些更改
  • 你给&lt;a&gt;元素赋予了哪些样式?
  • 已修复,谢谢!它在 CSS 中,我有一个带有 display: 块(用于另一个部分)的一般 {} 样式,添加了 .textDiv a{display: inline;},现在可以使用。

标签: php html mysql


【解决方案1】:

当你使用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;
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多