处理Laravel / Algolia中令人困惑的网址

时间:2016-06-30 20:07:40

标签: php laravel-5.2 slug algolia

我正在使用优秀的algolia / algoliasearch-laravel包装和laravel 5.2。

我上传到Algolia的我的一个“产品”在产品名称中有正斜杠:

  

Teal Stag开司米羊绒围巾/由埃尔金的Johnstons偷走

使用cviebrock / eloquent-sluggable包将其更改为以下URL:

  

/产品/妇女/山羊绒%20Patterned%20Scarves / TEAL-雄鹿绒-围巾++偷逐johnstons-的埃尔金

注意围巾和披肩之间的++。

当这个上传到Algolia时,我得到了这个:

objectID: 8122
name: "Teal Stag Cashmere Scarf/Stole by Johnstons of Elgin"
imgsrc: "Stag Teal Cashmere Stole (Small)_small.jpg"
rank: 0
url: "https://mywebsite.com/products/women/Cashmere Patterned Scarves/teal-stag-cashmere-scarfstole-by-johnstons-of-elgin"

看看algolia中的网址是不是正确的?我已经尝试用++进入网址,但我现在已经失去了如何继续下去。

1 个答案:

答案 0 :(得分:1)

在完成此操作之后,答案很简单,我的原始网址格式错误。我重新编写了使用Laravel 5.2中的str_slug函数生成URL的方式,并且一切都很好:

 /**
 * Generate a URL friendly "slug" from a given string.
 *
 * @param  string  $title
 * @param  string  $separator
 * @return string
 */
public static function slug($title, $separator = '-')
{
    $title = static::ascii($title);

    // Convert all dashes/underscores into separator
    $flip = $separator == '-' ? '_' : '-';

    $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);

    // Remove all characters that are not the separator, letters, numbers, or whitespace.
    $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));

    // Replace all separator characters and whitespace by a single separator
    $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);

    return trim($title, $separator);
}