【问题标题】:Any more efficient way for custom preg_replace function?自定义 preg_replace 函数有更有效的方法吗?
【发布时间】:2013-01-29 01:25:20
【问题描述】:

我计划在从我的 mysql 表中获取数据并将其打印为 html 时使用下面的自定义函数。由于 htmlspecialchars() 将标签转换为 html 实体,因此我将它们(p、br、strong)重新转换为标签。

我的问题是:它是否足够有效或者是否有其他更短或更有效的方法来实现这一目标?如果您知道的话,请您至少用关键字指导我吗?我可以在 php.net 和这个站点中寻找他的详细信息。

谢谢,问候

    function safe_output_from_mysql($safe_echo_to_html)
{
    $safe_echo_to_html = mb_convert_encoding($safe_echo_to_html, 'UTF-8', mb_detect_encoding($safe_echo_to_html));
    $safe_safe_echo_to_html = htmlspecialchars($safe_echo_to_html, ENT_QUOTES, "UTF-8");
    $safe_echo_to_html = preg_replace("&lt;br /&gt;","<br />",$safe_echo_to_html);
    $safe_echo_to_html = preg_replace("&lt;p&gt;","<p>",$safe_echo_to_html);
    $safe_echo_to_html = preg_replace("&lt;/p&gt;","</p>",$safe_echo_to_html);
    $safe_echo_to_html = preg_replace("&lt;strong&gt;","<strong>",$safe_echo_to_html);
    $safe_echo_to_html = preg_replace("&lt;/strong&gt;","</strong>",$safe_echo_to_html);
    return $safe_echo_to_html;
}

【问题讨论】:

  • 既然你没有使用正则表达式,你应该只使用str_replace

标签: php mysql preg-replace security performance


【解决方案1】:

无需多次调用 preg_replace()。您可以使用单个模式来匹配所有所需的标签:

preg_replace('/&lt;\s*(\/?(?:strong|p|br)\s*\/?)&gt;/i', '<\1>', $s);

当然,我假设您实际上打算使用正则表达式进行匹配。如果搜索字符串是纯文本,那么 strtr() 效率更高。

【讨论】:

    【解决方案2】:

    htmlspecialchars_decode:http://www.php.net/manual/en/function.htmlspecialchars-decode.php

    这个函数与 htmlspecialchars() 是相反的。它将特殊的 HTML 实体转换回字符。

    $str = "<p>this -&gt; &quot;</p>\n";
    
    echo htmlspecialchars_decode($str);
    

    上面的例子会输出:

    <p>this -> "</p>
    

    【讨论】:

    • 感谢您的回答,但我故意没有使用 htmlspecialchars_decode 函数;因为:想想一个坏用户将这段代码输入我的评论 textarea 如果我从我的 mysql 中解码所有内容,那么这意味着我很容易受到 XSS 攻击,对吧?所以我认为我不应该使用 htmlspecialchars_decode 函数。我从 php.net 中学到了逃避你需要的东西并再次解码你需要的东西。如果我错了,请纠正我。问候
    【解决方案3】:

    请看函数 htmlspecialchars_decode($str);功能。

    【讨论】:

    • 感谢您的回答,但我故意没有使用 htmlspecialchars_decode 函数;因为:想想一个坏用户将这段代码输入我的评论 textarea 如果我从我的 mysql 中解码所有内容,那么这意味着我很容易受到 XSS 攻击,对吧?所以我认为我不应该使用 htmlspecialchars_decode 函数。我从 php.net 中学到了逃避你需要的东西并再次解码你需要的东西。如果我错了,请纠正我。问候
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    相关资源
    最近更新 更多