gpt4 book ai didi

PHP - 在div中显示来自mysql文本字段的html

转载 作者:行者123 更新时间:2023-11-29 18:50:40 25 4
gpt4 key购买 nike

从 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;
}

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

关于PHP - 在div中显示来自mysql文本字段的html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44367237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com