PHP replace spaces in a string with dashes.

In order to replace the spaces in a string with dashes, we can use preg_replace or str_replace(). So check the example first.

Replace space with dash using str_replace() :

<?php
	$string = "replace whitespace with dash";
	$output = str_replace(' ', '-', $string);
	
	echo $output;
?>

Output:

PHP replace spaces in a string with dashes
replace-whitespace-with-dash

Replace space with dash using preg_replace() :

<?php
	$string = "replace whitespace with dash";
	$output = preg_replace('/(?<!\s) (?!\s)/', '-', $string);
	
	echo $output;
?>
replace-whitespace-with-dash

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment