Open In App

How to remove non-alphanumeric characters in PHP?

Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.

Examples:

Input : !@GeeksforGeeks2018?
Output : GeeksforGeeks2018

Input : Geeks For Geeks
Output : GeeksForGeeks

Syntax:

int preg_match( $pattern, $replacement_string, $original_string )

Parameter: This function accepts three parameter as mentioned above and described below:

Return value:

Method 1: The regular expression ‘/[\W]/’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (empty string).

$str = preg_replace( '/[\W]/', '', $str);

In the regular expression W is a meta-character that is preceded by a backslash (\W) that acts to give the combination a special meaning. It means a combination of non-alphanumeric characters.

Example:




<?php 
  
// string containing non-alphanumeric characters
$str="!@GeeksforGeeks2018?";
  
// preg_replace function to remove the
// non-alphanumeric characters
$str = preg_replace( '/[\W]/', '', $str);
  
// print the string
echo($str);
?>

Output:
GeeksforGeeks2018

Method 2: The regular expression ‘/[^a-z0-9 ]/i’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (null string).

$str = preg_replace( '/[^a-z0-9 ]/i', '', $str);

In the regular expression:

Example:




<?php 
  
// string containing non-alphanumeric characters
$str="!@GeeksforGeeks2018?";
    
// preg_replace function to remove the 
// non-alphanumeric characters
$str = preg_replace( '/[^a-z0-9]/i', '', $str);
   
// print the string
echo($str);
?>

Output:
GeeksforGeeks2018

Article Tags :