简体   繁体   English

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

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

I've some problem with displaying html tags after I retrieve them from a text field in my mysql DB. 从mysql数据库中的文本字段检索html标记后,我在显示html标记时遇到一些问题。

my code looks something like this: 我的代码看起来像这样:

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

So when the text field in mysql has only plain text, everything is fine, but when I add a link inside the text, I get a line break before and after the link tag, and the displayed text becomes line this: 因此,当mysql中的文本字段只有纯文本时,一切都很好,但是当我在文本内添加链接时,在链接标记之前和之后都会出现换行符,并且显示的文本变为以下行:

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

However, HTML code generated by the script is like this: 但是,脚本生成的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>

Do you guys have any idea why this happens and how to fix it? 你们知道为什么会发生这种情况以及如何解决吗? So that the text is displayed smoothly without line breaks? 这样文本可以流畅显示而不会出现换行符?

When you are using htmlspecialchars_decode all of the text's html is being decoded , so if you want to keep the decode function 当您使用htmlspecialchars_decode所有文本的html都将被解码,因此,如果要保留解码功能

1)Change the link in to how a normal link will look like , eg : yourwebsite.com/test.html don't add the tag 1)将链接更改为普通链接的外观,例如:yourwebsite.com/test.html不要添加标签

2) Don't echo string directly do this 2)不要直接回显字符串

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

3) Then pass the variable $text to code to detect links , here is one :- 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;
    }

You can change the code to adjust to your needs 您可以更改代码以适应您的需求

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

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