How to remove special characters and spaces in a text field using PHP

I need to remove all special characters and spaces in the text box for the form I am creating. How to do it in PHP.

+7
php
source share
3 answers

It really depends, I suppose you are working with $ _POST [] data and want to misinform these inputs? If so, I would definitely do something like:

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

This will separate everything except alpha / num, you can customize the regex to include other characters if you want. Some great examples of commonly used regular expressions can be found at: RegEx Library

If this is not exactly what you are looking for, or if you have other questions, let us know.

+32
source share

Use the following regex during data processing:

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

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

+7
source share
 $specialChars = array(" ", "\r", "\n"); $replaceChars = array("", "", ""); $str = str_replace($specialChars, $replaceChars, $str); 
+5
source share

All Articles