PHP program to remove non-alphanumeric characters from string

PHPServer Side ProgrammingProgramming

To remove non-alphanumeric characters from string, the code is as follows −

Example

 Live Demo

<?php
$my_str="Thisis!@sample*on&ly)#$";
$my_str = preg_replace( '/[^a-z0-9]/i', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo($my_str);
?>

Output

The non-alphanumeric characters removed gives the string as Thisissampleonly

The function ‘preg_replace’ is used to remove alphanumeric characters from the string. A regular expression is used to filter out the alphanumeric characters. The string is previously defined and the function ‘preg_replace’ is called on this and the reformed string is displayed on the console.

Example

 Live Demo

<?php
$my_str="This!#is^&*a)(sample*+_only";
$my_str = preg_replace( '/[W]/', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo($my_str);
?>

Output

The non-alphanumeric characters removed gives the string as Thisisasample_only

The only difference here is that a different regular expression is used. It means the same as the previous regular expression, but written in a different fashion.

raja
Published on 02-Jul-2020 06:52:25
Advertisements