Laravel Tutorials

Convert Special Characters to ASCII with Laravel's Str::transliterate Method

Published
Convert Special Characters to ASCII with Laravel's Str::transliterate Method image

Laravel's Str::transliterate method provides a simple solution for normalizing text content by converting special characters to their ASCII equivalents.

Convert special characters to ASCII:

use Illuminate\Support\Str;

$content = Str::transliterate('Café Ñoño & Résumé');
// Result: 'Cafe Nono & Resume'

Here's how you might use it in a content processing service:

class ContentProcessor
{
    public function processFormData(array $data)
    {
        return collect($data)->map(function ($value) {
            return is_string($value) 
                ? Str::transliterate($value)
                : $value;
        })->all();
    }

    public function createSlug(string $title)
    {
        return Str::slug(Str::transliterate($title));
    }

    public function normalizeSearchQuery(string $query)
    {
        return strtolower(Str::transliterate($query));
    }

    public function sanitizeKeywords(array $keywords)
    {
        return array_map(function ($keyword) {
            return Str::transliterate($keyword);
        }, $keywords);
    }
}

class ArticleController extends Controller
{
    public function create(Request $request, ContentProcessor $processor)
    {
        $processedData = $processor->processFormData([
            'title' => $request->title,
            'content' => $request->content,
            'keywords' => $request->keywords
        ]);

        Article::create($processedData);
    }
}

The transliterate method makes it easy to ensure consistent text formatting across your application.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article
Real-Time Inertia Props With Laravel Reverb image

Real-Time Inertia Props With Laravel Reverb

Read article