Removing unwanted characters on String using PHP

Remove unwanted characters using PHP

Use this php code to remove unwanted characters on your input content.

(a) Remove Non-numerical characters
$var=” 123!4565string990.00 “;
$req=preg_replace(“/[^0-9]/”,””,$var); or $req=preg_replace(“/\D/”,””,$var);
echo $req; //Result = 123456599000

(b) Remove Non-alphabetic characters
$var=” 123!4565string990.00 “;
echo $req; //Result = string

(c) Remove non-alphanumeric characters
$var=” 123!45@*&^65string990.00 “;
echo $req; //Result = 1234565string99000

(d) Remove white_space only
$var=” 123!45 @*&^65 string990.00 “;
echo $req; //Result = 123!45@*&^65string990.00 (Remove all white spaces in a varible)

Notes: syntax => preg_replace(expression,replace_content,variable);
1.Some Expressions are,
“/[0-9]/” or “/ \d/ g” => Select digits only
“/[^0-9]/” or “/ \D /g” => Select all non-digits
“/[a-zA-Z]/” => Select Alphabetics only
“/[^a-zA-Z]/” or “/ \D /g” => Select all non-alphabetics
“/[a-zA-Z0-9]/” or “/ \D /g” => Select all Alpha-numeric characters
“/[^a-zA-Z0-9]/” or “/ \D /g” => Select all Non-alphanumeric characters
2.Replace_Content => you can add any variable type as a replace content include white-space(” “) and empty field(“”).
3.Variable => You can use any assigned variable or direct values

Leave a Reply