How can PHP be used to implement slugs and routes for displaying article titles in URLs?

To implement slugs and routes for displaying article titles in URLs using PHP, you can create a function that generates a slug from the article title and then use a router to map the slug to the corresponding article. This way, you can have clean and user-friendly URLs that display the article titles.

// Function to generate slug from article title
function generateSlug($title) {
    $slug = strtolower(str_replace(' ', '-', $title));
    return preg_replace('/[^A-Za-z0-9-]+/', '', $slug);
}

// Router to map slugs to articles
$routes = [
    'article1' => 'Article 1 Title',
    'article2' => 'Article 2 Title',
    'article3' => 'Article 3 Title',
];

if(isset($_GET['slug']) && array_key_exists($_GET['slug'], $routes)) {
    $articleTitle = $routes[$_GET['slug']];
    echo "Displaying article: " . $articleTitle;
} else {
    echo "Article not found";
}