Home » Php » php – how to strip all characters except for alphanumeric and underscore and dash?

php – how to strip all characters except for alphanumeric and underscore and dash?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m not an expert with regex:(
I’m trying to to strip all characters from the string except for alpanumeric and underscore and dash.
Is this the correct syntax?:

preg_replace("/[^a-z0-9_-]+/i", "", $string);
How to&Answers:

Yes, but it can be optimised slightly:

preg_replace('/[^\w-]/', '', $string);

\w matches alphanumeric characters and underscores. This has the added advantage of allowing accented characters if your locale allows.

Answer:

What you have looks like it will work. You may want to add spaces since they’re not an alphanumeric character:

preg_replace("/[^a-z0-9_-\s]+/i", "", $string);

Answer:

Yes. 🙂

http://codepad.org/lkJTRP0P