Take the 2-minute tour ×

I want to convert all the non-alphanumerical characters to hyphens (-) (dashes) for an elegant URL. For this purpose I am using the following method:

$title = 'Any Authentic PHP Script / Third Party & @ 10 $ tool to'; 
$title .= 'Convert HTML to BBcode, BBcode to HTML';
$url = preg_replace("/[^0-9a-zA-Z ]/m", "", $title );
$url = preg_replace("/ /", "-", $url);

It outputs the following:


But, as you will have noticed, there are some unwanted double hyphens (--) and some triple hyphens (--) in the output. I want only one hyphen between each word. How can I achieve my target?

share|improve this question
Duplicate question - stackoverflow.com/a/6979888/2106973 –  Navnath Apr 27 '13 at 13:15

2 Answers 2

up vote 4 down vote accepted

For your code, just replace



$url = preg_replace("/\s+/", "-", $url);

And get all your spaces (and tabs and so on) convert to only one hyphen. \s means any space character, and + means one or more of the previous token

However, you can do better. Replace both your regexes into one preg_replace

$url = preg_replace("/\W+/m", "-", $title );

...because \W precisely mean non-alphanumeric characters.

In addition, if you also don't want underscores (_) in your result, use

$url = preg_replace("/[\W_]+/m", "-", $title );

As a side note, next time if you genuinely want to do


please do this instead

str_replace(" ", "-", $url);

Because str_replace is much faster than preg_replace and is even recommended from PHP docs:


If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

share|improve this answer
Shouldn't you use [\W_]+ instead since \W+ will not match underscores? –  Jerry Apr 27 '13 at 13:10
That's Excellent. Thanks. –  Rashid Farooq Apr 27 '13 at 13:12
@Jerry noted, included in my answer –  luiges90 Apr 27 '13 at 13:14

It's because first all non-alphanumerical characters are removed, so your string becomes

Any Authentic PHP Script  Third Party   10  tool to

You're seeing it already—leaving double spaces at some places.

Just do this:

preg_replace("/[^a-zA-Z0-9]+/", "-", $subject);

It replaces all occurences of one or multiple non-alphanumerical characters to a single dash.

share|improve this answer
You have a typo in your code, should be A-Z not A-A –  Kevin Vandenborne Feb 19 at 10:26
@KevinVandenborne Thanks! Fixed! –  MC Emperor Feb 19 at 15:33

Your Answer


