首頁 > 後端開發 > php教程 > 使用Laravel' s String()方法簡化字符串操縱

使用Laravel' s String()方法簡化字符串操縱

James Robert Taylor
發布: 2025-03-05 15:41:15
原創
639 人瀏覽過

Streamlining String Manipulation with Laravel's string() Method

laravel's request->string()方法提供了一種簡化的字符串操縱方法。它將輸入數據轉換為可弦的對象,從而使流利的方法鏈接以進行有效的轉換。 >

這個示例演示了基本用法:

// Basic transformation
$name = $request->string('name')
    ->trim()
    ->title()
    ->limit(50);

// Input:
$request->input('name') = '  jANE mARY smith   ';

// Output:
'Jane Mary Smith'
登入後複製
這是個人資料數據衛生中的一個實際應用:

<?php namespace App\Http\Controllers;

use App\Models\Profile;
use Illuminate\Http\Request;

class ProfileController extends Controller
{
    public function update(Request $request, Profile $profile)
    {
        $profile->update([
            'display_name' => $request->string('name')
                ->trim()
                ->title()
                ->limit(50)
                ->toString(),

            'username' => $request->string('username')
                ->trim()
                ->lower()
                ->replaceMatches('/[^a-z0-9_-]/', '')
                ->limit(20)
                ->toString(),

            'bio' => $request->string('bio')
                ->trim()
                ->stripTags()
                ->limit(160)
                ->toString(),

            'website' => $request->string('website')
                ->trim()
                ->lower()
                ->replace(['http://', 'https://'], '')
                ->before('/')
                ->toString()
        ]);

        return response()->json([
            'message' => 'Profile updated successfully',
            'profile' => $profile->fresh()
        ]);
    }
}
登入後複製
方法通過通過鍊式方法調用簡化輸入消毒和轉換來增強代碼的可讀性和可維護性,從而使字符串操縱更加清潔,更有效。

>

以上是使用Laravel&#039; s String()方法簡化字符串操縱的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板