laravel 在 URL 中用破折号 (-) 替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19080222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:29:45  来源:igfitidea点击:

Replace Spaces with Dash (-) in URL

phplaravellaravel-4eloquent

提问by TerryG

I'm working on my first Laravel 4 project and using the eloquent ORM to retrieve rows from the database using a route. Example:

我正在处理我的第一个 Laravel 4 项目,并使用 eloquent ORM 通过路由从数据库中检索行。例子:

Here is a route:

这是一条路线:

Route::get('{publisher}/{series}', function($publisher, $series)
{
$result = Comic::where('publisher', '=', $publisher)
->where('series', '=', $series)
->orderBy('issue', 'asc')
->get();

return View::make('comic')
->with('result', $result); 
});

This is supposed to be matching a url like site.com/marvel/amazing-spider-man

这应该匹配像 site.com/marvel/amazing-spider-man 这样的网址

Right now it only works for site.com/marvel/amazing spider-man or site.com/marvel/amazing%20spider-man

现在它只适用于 site.com/marvel/amazing spider-man 或 site.com/marvel/amazing%20spider-man

How can I make sure to only use the '-' urls? I believe what I need to do is:

如何确保只使用“-”网址?我相信我需要做的是:

a. write code that replaces the '-' with a %20 during the routing b. write code that replaces a %20 with a '-' during url generation

一种。编写在路由期间用 %20 替换“-”的代码 b. 编写在 url 生成期间用“-”替换 %20 的代码

Another consideration is that I don't really want my content to be accessible on both urls.

另一个考虑是我真的不希望我的内容在两个 url 上都可以访问。

回答by CupOfJoe

The reason why I think you are not getting the result you expect is because of the format in which the "series" name is stored in the database, remember that is looking for an exact match, so if you want to retrieve the results for:

我认为您没有得到您期望的结果的原因是因为“系列”名称存储在数据库中的格式,请记住这是在寻找完全匹配,因此如果您想检索以下结果:

http://www.site.com/marvel/amazing-spider-man

You will need to store it in the database as "amazing-spider-man" to avoid the extra step of removing dashes (-), if you don't like this format then you can do:

您需要将它作为“amazing-spider-man”存储在数据库中,以避免删除破折号 (-) 的额外步骤,如果您不喜欢这种格式,那么您可以这样做:

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

This will remove the dashes, but beware not to use dashes within the names because they will get removed, and now you can store the series name in the database as "amazing spider man".

这将删除破折号,但要注意不要在名称中使用破折号,因为它们会被删除,现在您可以将系列名称作为“神奇蜘蛛侠”存储在数据库中。

回答by Joeri

->with('result', Str::slug($result));

->with('result', Str::slug($result));

  • Str::slug(string $title, string $separator = '-')
  • Str::slug(string $title, string $separator = '-')

http://laravel.com/docs/4.2/helpers#strings

http://laravel.com/docs/4.2/helpers#strings