PHP使用str_slug而不更改Upper Cases

问题描述 投票:3回答:2

想要使用str_slug将文本更改为slug。它适用于不同的情况,但我希望它能在不改变UpperCases的情况下工作,即

例如:Hello --- World => Hello-World

有没有办法得到我想要的东西?

php string laravel
2个回答
3
投票

正如关于laracasts.com的问题所述,您可以创建自己的辅助函数版本,这样就省去了mb_strtolower()

public static function slug($title, $separator = '-', $language = 'en')
{
    $title = static::ascii($title, $language);
    // Convert all dashes/underscores into separator
    $flip = $separator == '-' ? '_' : '-';
    $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
    // Replace @ with the word 'at'
    $title = str_replace('@', $separator.'at'.$separator, $title);
    // Remove all characters that are not the separator, letters, numbers, or whitespace.

    // With lower case: $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));
    $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $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);
}

Working example

Original implementation


1
投票

继承人str_slug使用的实现:

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

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

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

    // Replace @ with the word 'at'
    $title = str_replace('@', $separator.'at'.$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);
}

只需从此方法类扩展或将其复制到您自己的新类,然后删除任何转换大小写的代码。

© www.soinside.com 2019 - 2024. All rights reserved.