How can the array_count_values() function be utilized in PHP for keyword extraction?

When extracting keywords from a text in PHP, the array_count_values() function can be utilized to count the frequency of each word in the text. By converting the text into an array of words and then using array_count_values(), we can easily determine the most common keywords.

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";

// Convert text to lowercase and remove punctuation
$text = preg_replace('/[^\w\s]/', '', strtolower($text));

// Convert text to array of words
$words = explode(" ", $text);

// Count frequency of each word
$wordCount = array_count_values($words);

arsort($wordCount); // Sort the array by frequency in descending order

// Get top 5 keywords
$keywords = array_slice(array_keys($wordCount), 0, 5);

print_r($keywords);