简体   繁体   English

如何在网址的连字符中替换空格

[英]How do I replace spaces into hyphens in an URL

I have some data that is inputted into to a database with spaces. 我有一些数据输入到带空格的数据库中。 eg 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. 然后,我需要从数据库中调用该数据并将其显示为链接,以便获得友好的URL。 I am not sure if I should do this with mod-rewrite or php. 我不确定是否应该使用mod-rewrite或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 预先感谢您的帮助

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 或者您可以使用urlencode

Try urlencode() 尝试urlencode()

urlencode($url)

You should probably use urlencode(), which will turn the spaces into %20. 您可能应该使用urlencode(),它将把空格变成%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. 但是,如果您想做自己想做的事情,则必须记住str_replace返回被替换的字符串,它不会修改您传入的var。

So you need $url = str_replace(' ', '-', $url); 所以你需要$ url = str_replace('','-',$ url);

A URL rewrite is not necessary. 不需要重写URL。 It sounds like your goal is to simply build a URL that looks something like this: 听起来您的目标只是建立一个看起来像这样的URL:

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

To replace only spaces with hyphens in $url, try 要仅用$ url中的连字符替换空格,请尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM