Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace regexp for dash

I am trying to replace anything in the string that is not a letter, number, or dash "-".

How do I modify this line to include the dash?

$link = preg_replace('/[^a-z0-9]/', "", strtolower($_POST['link_name']));

Do I just insert it in there?

$link = preg_replace('/[^a-z0-9-]/', "", strtolower($_POST['link_name']));
like image 372
MultiDev Avatar asked Jun 04 '12 13:06

MultiDev


2 Answers

You have to escape - since it's a special character for regexes:

$link = preg_replace('/[^a-z0-9\-]/', '', strtolower($_POST['link_name']));
like image 78
Wirone Avatar answered Sep 28 '22 05:09

Wirone


Just add - to the end of the class ([^a-z0-9-]).

- has no special meaning at the end of a class. Alternatively, escape it with a backslash.

like image 38
Niet the Dark Absol Avatar answered Sep 28 '22 04:09

Niet the Dark Absol