How to remove non-alphanumeric characters? How to remove non-alphanumeric characters? php php

How to remove non-alphanumeric characters?


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


For unicode characters, it is :

preg_replace("/[^[:alnum:][:space:]]/u", '', $string);


Regular expression is your answer.

$str = preg_replace('/[^a-z\d ]/i', '', $str);
  • 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.