How to I remove special characters and spaces on a textfield using PHP

前端 未结 3 622
鱼传尺愫
鱼传尺愫 2020-12-11 02:21

I need to remove all special characters and spaces on a textfield for a form I\'m building. How do I accomplish this in PHP.

相关标签:
3条回答
  • 2020-12-11 02:52

    This really depends, I assume you are working with $_POST[] data and wish to sanitize those inputs? If so I would definitely do something like:

    $var = preg_replace("/[^A-Za-z0-9]/", "", $var);
    

    That will strip out everything other than alpha/num, you can adjust the regex to include other characters if you wish. Some great examples of commonly used regular expressions can be found at: The RegEx Library

    If this isn't quite what you are looking for or have other questions let us know.

    0 讨论(0)
  • 2020-12-11 03:09

    Use the following regex during processing of the data:

    $data = preg_replace('/[^A-Za-z0-9]/', "", $data);
    

    This will remove all non-alphanumeric characters from the data.

    0 讨论(0)
  • 2020-12-11 03:11
    $specialChars = array(" ", "\r", "\n");
    $replaceChars = array("", "", "");
    
    $str = str_replace($specialChars, $replaceChars, $str);
    
    0 讨论(0)
提交回复
热议问题