自定义preg_replace函数的任何更有效的方法


Any more efficient way for custom preg_replace function?

我计划使用下面的自定义函数,同时从mysql表中获取数据&将其打印为html。由于htmlspecialchar()将标记转换为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;
}

不需要多次调用preg_replace()。你可以使用一个单一的模式来匹配所有想要的标签:

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

当然,我假设您实际上计划使用regex进行匹配。如果搜索字符串是纯文本,那么strtr()会更有效率。

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

此函数与htmlspecialchar()相反。它将特殊的HTML实体转换回字符。

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

上面的例子将输出:

<p>this -> "</p>

请参阅函数htmlspecialchars_decode($str);作用