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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题