Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one or more consecutive spaces with one single character?

Tags:

php

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?

like image 780
Ibrahim Azhar Armar Avatar asked Nov 22 '10 11:11

Ibrahim Azhar Armar


1 Answers

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
like image 53
Paul Dixon Avatar answered Nov 15 '22 06:11

Paul Dixon