Home » Php » string – Replace Dash with Space in PHP

string – Replace Dash with Space in PHP

Posted by: admin April 23, 2020 Leave a comment


I currently have this line in my code:

<div><a href="http://www.envisionforce.com/local/'.$row[website].'-seo-services">'.ucwords($row[website]).'</a></div>

And it will display a city name such as this:


But what I need is for it to display without the dashes and so that ucwords will capitalize the first letter of each word such as this:

Puiol Del Piu

It would be great if the code could be confined to this one line because I have a lot more going on with others stuff in the page as well.

How to&Answers:
echo '<div><a href="http://www.envisionforce.com/local/'.$row[website].'-seo-services">'.ucwords(str_replace("-"," ",$row[website])).'</a></div>';

In the above example you can use str_replace() to replace hyphens with spaces to create separate words. Then use ucwords() to capitalize the newly created words.




This str_replace does the job:

$string = str_replace("-", " ", $string);

Also, you can make it as a function.

function replace_dashes($string) {
    $string = str_replace("-", " ", $string);
    return $string;

Then you call it:

$varcity = replace_dashes($row[website]);
<div><a href="http://www.envisionforce.com/local/'.$row[website].'-seo-services">'.ucwords($varcity).'</a></div>


replace dash with space

str_replace("-"," ",$row[text])

replace space with dash

str_replace(" ","-",$row[text])


str_replace (‘Find what you want to replace’, ‘Replace with ‘, ‘Your array or string variable’);

If you want to replace dash with space, you can use this:

str_replace("-"," ",$row[text])

If you want to replace space with dash, use this:

str_replace(" ","-",$row[text])

Use ucwords() to capitalize words.