Php:删除所有标签,但删除"a href"在文本中 [英] Php: remove all tags, but "a href" in a text

查看:78
本文介绍了Php:删除所有标签,但删除"a href"在文本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:

我有一个文本区域,用户可以在其中输入他想要的任何内容.

I have a textarea where the user can enter whatever he wants.

当他发送此文本(POST方法)时,在服务器端,我完全不过滤 ,然后再将其写入数据库(因为我想保持用户输入的内容完整"(也许可以用作用户尝试入侵的证明).

When he sends this text (POST method), on the server side I don't filter it at all before writing it into the database (because I want to keep "intact" what the user entered (maybe it can be used as a proof he tried to hack or whatever)).

然后,在输出它之前,我使用以下功能:

Then, before outputting it, I use this function:

public function textForWeb($texte,$br=true)
{
  if ($br) {
    return
      mb_ereg_replace("((\r)?\n)", "<br />",
        htmlentities(
          stripslashes($texte),
          ENT_QUOTES, 'UTF-8'
        )
      );
  }
  else {
    return
      htmlentities(
        stripslashes($texte),
        ENT_QUOTES, 'UTF-8'
      );
  }
}

因此,文本已正确过滤,并保持UTF-8编码.

So the text is properly filtered and stays UTF-8 encoded.

但是问题是我希望 所有 这些文本:<a href="http://url">xxx</a>保持不变. IE.当我将其显示时,该链接(并且仅包含"http://"和 里面没有javascript 的链接)将是可点击的".

But the problem is that I'd like all these text: <a href="http://url">xxx</a> to be untouched. I.e. when I will display it, the link (and only links with "http://" and no javascript inside) will be "clickable".

例如,您可以看到它现在的显示方式

For example, you can see how it is displayed now here. See last line of the announce? I'd like the link to the website to be "clickable".

你会怎么做?

推荐答案

只需在您的htmlentities()函数之后添加preg_replace()函数即可还原转义的 a 标签

Just add a preg_replace() function to revert the escaped a tags after your htmlentities() function

$output = textForWeb($output);
$output = preg_replace('#&lt;a href=&quot;(?=https:\/\/|http:\/\/)(.*?)&quot;&gt;(.*?)&lt;/a&gt;#i', '<a href="$1">$2</a>', $output);

echo $output;

这样,您仍然可以以安全的方式转义所有其他HTML(而不是使用strip_tags()函数.)

That way you can still escape all other HTML in a safe way (instead of using strip_tags() function.)

此preg_replace()函数搜索链接到以http://或https://开头的页面的 a 标记,然后将转义的特殊字符替换为<,>和,链接再次可点击.

This preg_replace() function searches for a tags linking to pages starting with http:// or https:// and then replaces the escaped special characters with <, > and ", making the link clickable again.

这篇关于Php:删除所有标签,但删除"a href"在文本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆