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:
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