如何在URL中将空格替换为连字符

I have some data that is inputted into to a database with spaces. e.g. first and last names. I then need to call that data from the database and display it as a link so i have a friendly URL. I am not sure if I should do this with mod-rewrite or php. What is the best solution?

A solution like below doesn't seem to work

str_replace('- ','-',$url);

echo "<p><span class=\"barting\">"."<a href=$url=\"jobs/".$row['jobid']."/".$row['title']."\">".$row['title']."</a></span>";

echo $url

Thanks for help in advance

Try urlencode()

urlencode($url)

You wrote

str_replace('- ','-',$url);

But this code don't replace white spaces, to replace white spaces you should use:

$url = str_replace(' ','-',$url);

or you can use urlencode

You should probably use urlencode(), which will turn the spaces into %20. But if you want to do what you're doing, you have to remember that str_replace RETURNS the replaced string, it does not modify the var you pass in.

So you need $url = str_replace(' ', '-', $url);

A URL rewrite is not necessary. It sounds like your goal is to simply build a URL that looks something like this:

http://www.example.com/firstname-lastname/jobs/1234567/sometitle

To replace only spaces with hyphens in $url, try

str_replace(" ", "-", $url);