dongpangbu4016 2016-05-31 02:46
浏览 67
已采纳

正则表达式转换htmlspecialchars转义后的字符

I take user input on my website and I allow formatting through a WYSIWYG editor.

Now I run the entire post I get in PHP through htmlspecialchars with ENT_quotes.

From there I would like to run a regex to convert my allowed rules back to real html.

So that

<p>TEXT</p> 

Thanks!

becomes

<p>TEXT</p>

Is there way to do this with regex? I am not familair with it. But basically look for the escaped tags and replace them with real tags, while keeping everything in the middle?

Edit: I want the regex to make the valid HTML codes. First I run the entire thing through htmlspecialchars to be 100% secure and get entities version of all < & > characters. Then I want a regex to convert ONLY the tags I want back to normal. I do not want to decode all entities back to their regular, I only want to decode the tags I want. so for example a regex search for &lt;p&gt;TEXT&lt;/p&gt; back to <p>TEXT</p> - I don't want to reconvert just the <, &, > themselves. I want to reconvert only the tags I want. Which in this example is the paragraph tags.

  • 写回答

2条回答 默认 最新

  • donglun2010 2016-05-31 03:08
    关注

    I think this regex should work for what you've decribed:

    /&lt;(\/?)(allowed_tags_here_seperated_by_|)&gt;/
    

    Regex Demo: https://regex101.com/r/uX7cT1/1
    PHP Demo: https://eval.in/579884

    PHP Usage:

    $allowed_tags = array('p', 'h1');
    $regex = '/&lt;(\/?)(' . implode('|', $allowed_tags) . ')&gt;/';
    $test_string = '&lt;p&gt;TEXT&lt;/p&gt; This & that don\'t < decode > these though <h2> &lt;h1&gt; &lt;p class=&quot;test&quot;&gt;';
    echo preg_replace($regex, '<$1$2>', $test_string);
    

    Oh, this also doesn't take into account self closing elements. <br />, <hr />, <img stuff />, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?