Convert Special Characters to ASCII with Laravel's Str::transliterate Method
Last updated on by Harris Raftopoulos
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.