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

I want to create a string such as a URL that supports SEO. I want some empty space to be removed, the only space that needs to be replaced with a hyphen ( -), then strtolowerno special characters should be allowed.

For this, I currently have 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 remove this space and replace it with only one space. In short, I am trying to reach an SEO friendly URL such as a string. How to do it?

+5
source share
3 answers

preg_replace ...

 $string = preg_replace('/\s+/', '-', $string);
+18
echo preg_replace('~(\s+)~', '-', $yourString);
0

, , "slugify" . SO google "php slugify" "php slug".

0
source

All Articles