PHP - 从数据库输入和更新中过滤掉不需要的元素

I use the below method to strip away unwanted characters from everything that gets inserted or updated in a database.

To be honest I only want to allow the following characters other than regular letters and numbers: ', -, ), :... and a few others. Pretty much characters which will allow someone to write a regular phrase.

Am I going at it the right way? The preg_replace currently strips away spaces from strings. How can I make it stop? How can I add wanted characters to preg_replace?

public function strip($arr = array())
{
    if (!is_array($arr) || !count($arr))
    {
        return array();
    }

    $returnArray = array();

    foreach($arr as $key => $val)
    {
        $val = $this->db->mysqli->real_escape_string($val);
        $val = strip_tags($val);
        //$val = preg_replace("/[^A-Za-z0-9]/", '', $val);

        $returnArray[$key] =  $val;

    }

    return $returnArray;

}

[^A-Za-z0-9\s] will allow characters from A-Z or a-z or numbers from 0-9 and whitespaces. the \s stands for whitespaces if you want to add certain symbols you simply need to escape them with a \ if they are used in regex like the $ it would look like this [^\$]

If you need help creating regex you can use Regex101.com

How about:

$val = preg_replace("/[^A-Za-z0-9'):\s-]/", '', $val);

This will replace every thing that is not alphanumeric or '):- or spaces by nothing. You may add other wanted characters in the character class.