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
  • 620,600
  • 104
  • 758
  • 828
Ibrahim Azhar Armar
  • 24,538
  • 34
  • 126
  • 199
  • 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
  • 287,944
  • 49
  • 307
  • 343
0
echo preg_replace('~(\s+)~', '-', $yourString);
powtac
  • 39,317
  • 26
  • 112
  • 166
0

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

Yeroon
  • 3,185
  • 2
  • 21
  • 29