Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert spaces to dash and lowercase with PHP
In PHP, you can convert spaces to dashes and make text lowercase using a combination of str_replace() and strtolower() functions. This is commonly used for creating URL-friendly strings or slugs.
Basic Approach
The most straightforward method is to combine strtolower() with str_replace() to first convert the string to lowercase, then replace spaces with dashes ?
<?php
$str = 'Hello Have A Good Day Everyone';
$result = str_replace(' ', '-', strtolower($str));
echo $result;
?>
hello-have-a-good-day-everyone
Using preg_replace() for Multiple Spaces
For handling multiple consecutive spaces, preg_replace() with regular expressions provides better control ?
<?php
$str = 'Hello Have Multiple Spaces';
$result = strtolower(preg_replace('/\s+/', '-', $str));
echo $result;
?>
hello-have-multiple-spaces
Complete URL Slug Function
Here's a more robust function that handles special characters and creates clean URL slugs ?
<?php
function createSlug($text) {
// Replace non-alphanumeric characters with dashes
$text = preg_replace('/[^a-zA-Z0-9\s]/', '', $text);
// Replace spaces with dashes
$text = preg_replace('/\s+/', '-', $text);
// Convert to lowercase
return strtolower($text);
}
$title = 'Hello World! How Are You?';
echo createSlug($title);
?>
hello-world-how-are-you
Comparison of Methods
| Method | Handles Multiple Spaces | Removes Special Characters |
|---|---|---|
str_replace() |
No | No |
preg_replace() |
Yes | With proper pattern |
| Custom function | Yes | Yes |
Conclusion
Use str_replace() with strtolower() for simple space-to-dash conversion. For more complex requirements like URL slugs, combine preg_replace() with additional cleaning to handle special characters and multiple spaces effectively.
