Search the blog

Cleaning up strings is important in any dynamic web application. I was surprised to find there is no in-built way to only allow arbitrary characters in a string using PHP. Using the function below, create a string of characters that you want to allow and pass that and your string to the function.

function allowChars($var, $allowed) {

    $cleaned = "";
    $pos = 0;

    do {

        $char = substr($var, $pos, 1);

        if(strspn($char, $allowed, 0, strlen($allowed)) > 0) {

            $cleaned = $cleaned . $char;

        }

        $pos = $pos + 1;

    }
    while ($pos < strlen($var));

    return $cleaned;

}

Here are a few examples:

// Allow numbers only
$var =  allowChars($var, '0123456789'); 

// Allow letters only
$var =  allowChars($var, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

// Make suitable as a URI
$var =  allowChars(strtolower($var), 'abcdefghijklmnopqrstuvwxyz0123456789-_.~');
This function is case sensitive so, for example, a and A are treated as different characters
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.