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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Load Eloquent Models From Form Request Input in Laravel image

Load Eloquent Models From Form Request Input in Laravel

Read article
Laravel FFmpeg 9: Encode Video and Stream HLS and DASH image

Laravel FFmpeg 9: Encode Video and Stream HLS and DASH

Read article
Migration Durations and Job Memory Usage in Laravel 13.45 image

Migration Durations and Job Memory Usage in Laravel 13.45

Read article
Laravel CLI: One Binary for New PHP and Rust Laravel Apps image

Laravel CLI: One Binary for New PHP and Rust Laravel Apps

Read article
Phactorial: Render LaTeX Math to SVG and PNG in PHP image

Phactorial: Render LaTeX Math to SVG and PNG in PHP

Read article
Laravel, reimagined image

Laravel, reimagined

Read article