PHP使用str_slug而不更改Upper Cases

时间:2018-01-26 14:28:58

标签: php string laravel

想要使用str_slug将文本更改为slug。对于不同的情况,它的工作完全,但我希望它能够工作而不会更改UpperCases ,即

ex: Hello --- World => 您好,世界

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

2 个答案:

答案 0 :(得分: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 :(得分: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);
}

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