You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9.x中如何阻止Str::slug转换非英文字符串为英文?

在Laravel 9.x中保留非英文字符生成Slug

Laravel默认的Str::slug方法处理非英文字符(如波斯语)时,会自动将其转写为ASCII字符,若想保留原语言字符,可通过以下两种方式实现:

方法一:自定义Slug生成函数

直接编写一个仅处理空格、特殊字符和分隔符的函数,跳过ASCII转写步骤:

function preserve_unicode_slug($title, $separator = '-')
{
    // 移除HTML标签(若存在)
    $title = strip_tags($title);
    
    // 将空格、下划线、短横线统一替换为指定分隔符
    $title = preg_replace('/[\s_]+/', $separator, $title);
    
    // 保留Unicode字母、数字及分隔符,移除其他特殊字符
    $title = preg_replace('/[^\p{L}\p{N}' . preg_quote($separator, '/') . ']/u', '', $title);
    
    // 合并连续的分隔符为单个
    $title = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $title);
    
    // 移除首尾分隔符并转小写(小写转换可选,按需调整)
    return mb_strtolower(trim($title, $separator));
}

使用示例:

// 输入波斯语:"زن زندگی آزادی"
echo preserve_unicode_slug("زن زندگی آزادی"); 
// 输出:"زن-زندگی-آزادی"

方法二:全局扩展Str类的Slug方法

如果希望全局复用保留非英文字符的slug逻辑,可在AppServiceProvider的boot方法中添加自定义宏:

use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Str::macro('unicodeSlug', function ($title, $separator = '-') {
            $title = strip_tags($title);
            $title = preg_replace('/[\s_]+/', $separator, $title);
            $title = preg_replace('/[^\p{L}\p{N}' . preg_quote($separator, '/') . ']/u', '', $title);
            $title = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $title);
            return mb_strtolower(trim($title, $separator));
        });
    }
}

之后即可全局调用:

echo Str::unicodeSlug("زن زندگی آزادی");

核心逻辑说明

默认Str::slug的转写行为依赖Str::ascii()方法,该方法会把Unicode字符转换为最接近的ASCII等效字符。通过跳过这一步骤,我们就能在完成slug格式化的同时,保留原语言的字符。

内容的提问来源于stack exchange,提问作者Pooya Behravesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:55:19