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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article