Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove non-alphanumeric characters?

Tags:

string

regex

php

I need to remove all characters from a string which aren't in a-z A-Z 0-9 set or are not spaces.

Does anyone have a function to do this?

like image 855
zuk1 Avatar asked Mar 18 '09 16:03

zuk1


People also ask

How do you get rid of non-alphanumeric?

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.

How do you remove a non-alphanumeric character from a string?

Using Regular Expression We can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string. Replace the regular expression [^a-zA-Z0-9] with [^a-zA-Z0-9 _] to allow spaces and underscore character.

How do I remove non characters from a string?

To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.


2 Answers

Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.

preg_replace("/[^A-Za-z0-9 ]/", '', $string); 
like image 68
Chad Birch Avatar answered Sep 18 '22 15:09

Chad Birch


For unicode characters, it is :

preg_replace("/[^[:alnum:][:space:]]/u", '', $string); 
like image 43
voondo Avatar answered Sep 17 '22 15:09

voondo