Table of Contents
Using str_replace() Method
Use the str_replace() function to replace with underscore in PHP, for example: str_replace(" " , "_", $str). str_replaces() returns new String with old character space( ) replaced by underscore(_)
|
1 2 3 4 5 6 7 8 9 10 |
<?php $str = "Hello world from Java2blog"; # Replace space with underscore $str = str_replace(" " , "_", $str); echo $str; ?> |
|
1 2 3 |
Hello_world_from_Java2blog |
We used str_replace() to replace space with underscore in PHP.
str_replace() replaces all instances of search string with replacement String. It takes three arguments:
the string to search : space( )
the string to replace: underscore(_)
the string to be searched: Input String
str_replace() returns a new String, it does not alter contents of original String.
Using preg_replace() Method
Use the preg_replace() function to replace space with underscore in PHP. This approach is useful when you want to remove multiple spaces with single underscore.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $str = "Hello world from Java2blog"; # Replace space with underscore $str = preg_replace('/\s+/', '_', $str); echo $str; ?> ?> |
|
1 2 3 |
Hello world, from Java2blog |
We used preg_replace() with regular expression /\s+/ to replace space with underscore.
Here is image which represents regex:

preg_replace() function takes a regular expression as an input and replaces all matches with the specified string
preg_replace() replaces all instances of search pattern with replacement String. It takes three arguments:
regular expression : "/\s+/
the string to replace, underscore
the string to be searched: Input String
preg_replace() returns a new String, it does not change contents of original String.
That’s all about how to replace space with underscore in PHP