5

I want to generate the string like SEO friendly URL. I want that multiple blank space to be eliminated, the single space to be replaced by a hyphen (-), then strtolower and no special chars should be allowed.

For that I am currently the code like this:

$string = htmlspecialchars("This    Is The String");
$string = strtolower(str_replace(htmlspecialchars((' ', '-', $string)));

The above code will generate multiple hyphens. I want to eliminate that multiple space and replace it with only one space. In short, I am trying to achieve the SEO friendly URL like string. How do I do it?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
  • Related: http://stackoverflow.com/questions/741553/how-can-i-convert-two-or-more-dashes-to-singles-and-remove-all-dashes-at-the-begi, http://stackoverflow.com/questions/4051889/regular-expression-any-text-to-url-friendly-one, et al. – Gumbo Nov 22 '10 at 11:14

3 Answers3

19

You can use preg_replace to replace any sequence of whitespace chars with a dash...

 $string = preg_replace('/\s+/', '-', $string);
  • The outer slashes are delimiters for the pattern - they just mark where the pattern starts and ends
  • \s matches any whitespace character
  • + causes the previous element to match 1 or more times. By default, this is 'greedy' so it will eat up as many consecutive matches as it can.
  • See the manual page on PCRE syntax for more details
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
0
echo preg_replace('~(\s+)~', '-', $yourString);
powtac
  • 40,542
  • 28
  • 115
  • 170
0

What you want is "slugify" a string. Try a search on SO or google on "php slugify" or "php slug".

Yeroon
  • 3,223
  • 2
  • 22
  • 29