Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

pcre

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);
like image 520
Stann Avatar asked May 19 '11 18:05

Stann


2 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.

like image 66
lonesomeday Avatar answered Oct 03 '22 00:10

lonesomeday


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);
like image 29
Eric Conner Avatar answered Oct 02 '22 23:10

Eric Conner