有没有更好的方法来完成下面这个简单的任务?喜欢数组还是其他方法?
<?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/