duanbo5230 2015-09-21 11:22
浏览 22

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;

}
  • 写回答

2条回答 默认 最新

  • douzhiling3166 2015-09-21 11:33
    关注

    [^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

    评论

报告相同问题?