01 February 2017

How to Replace space with Dash in PHP

php logo
It is very common requirement to do a task where you need to Replace space with Dash in PHP.

PHP has a function str_replace() function which takes 3 parameters:
 i) look for that character
 ii) replace with the character
 iii) source string
Replace space with Dash in PHP
Replace space with Dash in PHP

For example : If the string is "Dhaka is the capital city of Bangladesh"
then the result will be "Dhaka_is_the_capital_city_of_Bangladesh"

Example code :
<?php
    $str = "Dhaka is the capital city of Bangladesh":
    $result = str_replace(" ", "-", $str);
   
    echo $result ;
?>

Output:
Dhaka_is_the_capital_city_of_Bangladesh

ASCII code of dash/Hyphen symbol :
&#150;

Syntax:


str_replace( find, replace, string, count )


find        the value to look for
replace  the value to change with
string     the value to search for
count      to count the number of times it occurs


Other PHP related post:




(If you found this article useful then share with your friends.)

1 comment:

mark said...

Thanks, this was the most clear and precise example I could find on the interwebs, works great, thanks!