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

发布于 2024-09-11 05:32:42 字数 386 浏览 3 评论 0原文

我有一些数据被输入到带有空格的数据库中。例如名字和姓氏。然后我需要从数据库中调用该数据并将其显示为链接,这样我就有了一个友好的 URL。我不确定是否应该使用 mod-rewrite 还是 php 来完成此操作。最好的解决方案是什么?

像下面这样的解决方案似乎不起作用

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

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

echo $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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

踏月而来 2024-09-18 05:32:42

您编写了

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

但此代码不会替换空格,要替换空格,您应该使用:

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

或者您可以使用 urlencode

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

幽蝶幻影 2024-09-18 05:32:42

尝试 urlencode()

urlencode( $url)

Try urlencode()

urlencode($url)

泪之魂 2024-09-18 05:32:42

您可能应该使用 urlencode(),它将空格变成 %20。但是如果你想做你正在做的事情,你必须记住 str_replace 返回替换的字符串,它不会修改你传入的 var。

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

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);

誰認得朕 2024-09-18 05:32:42

无需重写 URL。听起来你的目标是简单地构建一个看起来像这样的 URL:

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

To Replace only space with hyphens in $url, try

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文