03. Clean Code URL Slug Generator 03. Clean Code URL Slug Generator
Medium
+20 Points
Deskripsi Tantangan Problem Description
Buat fungsi `generateSlug($title)` yang mengubah judul artikel menjadi format URL slug (lowercase, spasi diganti strip `-`, hapus karakter khusus selain huruf & angka).
Create a function `generateSlug($title)` that converts a title into a clean URL slug (lowercased, spaces replaced by `-`, non-alphanumeric characters stripped).
Example Test Cases
Input: ["Belajar PHP Modern 2026!"]
Expected Output: "belajar-php-modern-2026"
Input: ["Laravel 13 & SOLID Principles"]
Expected Output: "laravel-13-solid-principles"
- Gunakan strtolower() untuk lowercase.
- Gunakan preg_replace() untuk menghapus karakter non-alphanumeric lalu ganti spasi dengan strip.
- Bisa gunakan trim() untuk menghilangkan strip di ujung string.
- Use strtolower() for lowercasing.
- Use preg_replace() to sanitize non-alphanumeric chars and convert spaces to dashes.
- Use trim() to remove trailing dashes.
<?php
function generateSlug(string $title): string {
$slug = strtolower($title);
$slug = preg_replace('/[^a-z0-9\s-]/', '', $slug);
$slug = preg_replace('/[\s-]+/', '-', $slug);
return trim($slug, '-');
}
solution.php
Test Case #
Input:
Expected:
Actual Output:
Error: