php - 可以改进此 PHP 代码吗?

标签 php

有没有更好的方法来完成下面这个简单的任务?喜欢数组还是其他方法?

<?PHP
// current way
if ($city != NULL) {
    $city = FilterALLHTML($city);
}
if ($state != NULL) {
    $state = FilterALLHTML($state);
}
if ($title != NULL) {
    $title = FilterALLHTML($title);
}
if ($division != NULL) {
    $division = FilterALLHTML($division);
}
?>

这是我当前的功能

function FilterALLHTML($document) {
    //old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
    $text = strip_tags($document);
    $search = array ("/f.?u.?c.?k/i",
                 "/(s|$).?h.?i.?t/i",
                 '/(potspace|mycrib|palbolt)/i');
    $text = preg_replace ($search, '', $text);  
    return $text;
}

更新 - 好的我的新功能在这篇文章的建议之后谢谢大家

function FilterALLHTML($var) {
    //old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
    if ($var != null){
        $text = strip_tags($var);
        $search = array ("/f.?u.?c.?k/i",
                     "/(s|$).?h.?i.?t/i",
                     '/(potspace|mycrib|palbolt|pot space)/i');
        $text = preg_replace ($search, '', $text);  
        return $text;
    }
    return null;
}

最佳答案

更改您的 FilterALLHTML 函数以执行 null 检查并让它返回 null? 然后你可以扔掉所有的 if

例子:

function FilterALLHTML($input)
{
    if ($input === null)
        return null;

    // Original code, I'll just use strip_tags() for a functional example
    return strip_tags($input);
}

编辑:

我想分享可变变量的替代方法,因为我真的不喜欢使用字符串文字而不是变量名的想法。一路引用:)

function FilterALLHTML(&$text)
{
    if ($text !== null)
    {
        // Omitted regex bit for simplicity
        $text = strip_tags($text);
    }
}

$city = "<b>New York</b>";
$state = null;
$title = "<i>Mr.</i>";

$fields = array(&$city, &$state, &$title);
foreach ($fields as &$var)
    FilterALLHTML($var);

(注意:FilterALLHTML 实现与第一个示例不同)

关于php - 可以改进此 PHP 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1198548/

相关文章:

php - 我们如何在 cakephp 的 Controller 名称前添加一些文本?

php - PHP 中的 MP3 和 OGG 标签

javascript - Laravel - href 被忽略的子文件夹问题

php - 使用 PDO 更新 msql 方法

处理缺少参数的 PHP 错误

php - 点击 "Place Order"后转换货币

php - 如何使用 Magento 测试 cron?

javascript - 指定 for 循环的终点有哪些优点和缺点?

php - 如何创建从 nodejs mysql 模块获取的正确的 json 类型数据?

php - Laravel : unforeseen problems from echoing HTML in controller vs. 传递数据查看?