Replace Space with Underscore in PHP

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(_)



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.


?>
Hello world, from Java2blog

We used preg_replace() with regular expression /\s+/ to replace space with underscore.

Here is image which represents regex:
Regex for replacing multiple spaces with one underscore

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.