• How to remove non-alphanumeric characters from a string

SOLUTION 1:

  •  To remove non-alphanumeric characters from a string,first you need to basically defined it as a regex.
JAVASCRIPT CODE
preg_replace("/[^A-Za-z0-9 ]/", '', $string);

  • For unicode characters, we have to use the below example:
javascript code
 preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
[ad type=”banner”]

   Here is an example:

javascript code
$str = preg_replace('/[^a-z\d ]/i', '', $str);

we need to  note of the following

  • The i stands for case insensitive.
  • ^ means, does not start with.
  • \d matches any digit.
  • a-z matches all characters between a and z. Because of the i parameter you don’t have to specify a-z and A-Z.
  • After \d there is a space, so spaces are allowed in this regex

  • here’s a really simple regex for remove non-alpha numeric characters:
javascript code
  \W|_

and used as you need it (with a forward / slash delimiter).

javascript code
 preg_replace("/\W|_/", '', $string);
[ad type=”banner”]
  • Test it here with this great tool that explains what the regex is doing:

http://www.regexr.com/

  • PHP function that strips a string of all characters other than alphanumeric characters:
javascript code
function onlyAlphanumericAndSpaces($text) 
{
# allow only alphanumeric
return ereg_replace("[^A-Za-z0-9 ]", "", $text );
}

  • We can also use the below code to Remove All Non-Numeric Characters
javascript code
/**
* Remove all characters except numbers.
*
* @param string $string
* @return string
*/
function stripNonNumeric( $string )
{
return preg_replace( "/[^0-9]/", "", $string );
}
[ad type=”banner”]

  • This code will delete any non-alphanumeric characters specified between the brackets, and then output/return the clean version.

The code:

php code
<?php $string = "Here! is some text, and numbers 12345, and symbols !£$%^&";
$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
echo $new_string ?>

 

Categorized in: