Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
PHP program to remove non-alphanumeric characters from string
To remove non-alphanumeric characters from string, the code is as follows −
Example
<?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
<?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.
Advertisements
