簡體   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