JAVASCRIPT

[ Solved -7 Answers] – How to remove non-alphanumeric characters from a string

How to remove non-alphanumeric characters from a string - To remove non-alphanumeric characters from a string, you need to basically defined it as a regex.

  • 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);

   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);
  • 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 );
}

  • 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 ?>

 

READ  [Solved- 4 Answers] how to set select element as readonly

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment