PHP

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
<?php
$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
<?php
$var=” 123!4565string990.00 “;
$req=preg_replace(“/[^a-zA-Z]/”,””,$var);
echo $req; //Result = string
?>

(c) Remove non-alphanumeric characters
<?php
$var=” 123!45@*&^65string990.00 “;
$req=preg_replace(“/[^a-zA-Z0-9]/”,””,$var);
echo $req; //Result = 1234565string99000
?>

(d) Remove white_space only
<?php
$var=” 123!45 @*&^65 string990.00 “;
$req=preg_replace(“/\s/,””,$var);
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