Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this PHP code be improved?

Tags:

php

Is there a better way to do this simple task below? Like with an array or even another method?

<?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);
}
?>

Here is my current function

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;
}

UPDATE - Ok my new function after the suggestions from this post thanks guys

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;
}
like image 906
JasonDavis Avatar asked Nov 28 '22 01:11

JasonDavis


2 Answers

Change your FilterALLHTML function to do the null check and have it return null? Then you can throw away all the ifs.

Example:

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

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

Edit:

I felt like sharing an alternative to variable variables, as I don't really like the idea of using string literals instead of variable names. References all the way :)

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);

(note: FilterALLHTML implementation differs from first example)

like image 80
Thorarin Avatar answered Dec 09 '22 01:12

Thorarin


Yes, use PHP's variable variables.

$vars = array('city','state','title','division');
foreach($vars as $v) {
    if ($$v != null) $$v = FilterAllHTML($$v);
}

If you know for a fact that all the variables have been previously defined, then you don't need the null check. Otherwise, the null check will prevent E_NOTICE errors from triggering.

like image 39
zombat Avatar answered Dec 09 '22 00:12

zombat