PHP nl2br 用于文本内容,但使其排除 javascript 内容

发布于 2025-01-13 14:04:19 字数 673 浏览 2 评论 0原文

我需要对来自数据库的页面内容使用 nl2br 函数。但是
标记也添加到了 javascript 内容中。

<script type="text/javascript"><br />
let test = "test";<br />
let menu = "menu";<br />
</script>

首先,为了将 br 添加到所有内容,然后从 javascript 内容中删除 br,我确实尝试了以下操作:

<?php
//content coming from db
$content = nl2br($content);
$content = preg_replace("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m", str_replace("<br />", "", nl2br($content)), $content);
echo $content;
?>

结果:br 未添加到 javascript 中,但 javascript 和文本内容确实出现了两次(br 不适用于第一个文本内容,但适用于第二个文本内容)文本内容)

如何在 javascript 代码中排除 br?

I need to use nl2br function on page content coming from DB. But <br /> tag added to into javascript content too.

<script type="text/javascript"><br />
let test = "test";<br />
let menu = "menu";<br />
</script>

Firstly for make add br to all content and than remove br from javascript content, I did try this:

<?php
//content coming from db
$content = nl2br($content);
$content = preg_replace("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m", str_replace("<br />", "", nl2br($content)), $content);
echo $content;
?>

Result: br not added into javascript but javascript and text content did come twice (br didn't worked on first text content but worked on second text content)

How can I exclude br in javascript code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停滞 2025-01-20 14:04:19

假设您的正则表达式满足您的需求,您可以使用 preg_replace_callback 来实现您想要的。

//content coming from db
$content = preg_replace_callback("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m",function($matches){return str_replace('<br />','',$matches[0]);},nl2br($content));

Assuming your regex suites your need, you can use preg_replace_callback to achieve what you want.

//content coming from db
$content = preg_replace_callback("/<script\b[^>]*>([\s\S]*?)<\/script\b[^>]*>/m",function($matches){return str_replace('<br />','',$matches[0]);},nl2br($content));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文