How can regular expressions be used to search for duplicate words in a string in PHP?

Regular expressions can be used to search for duplicate words in a string by capturing each word and then using backreferences to check for repetitions. By using the preg_match_all function in PHP with a regular expression pattern that captures words and checks for duplicates, we can easily identify any repeated words in the given string.

$string = "hello world world PHP PHP PHP";
$pattern = '/\b(\w+)\b(?=.*\b\1\b)/i';

if (preg_match_all($pattern, $string, $matches)) {
    $duplicates = array_unique($matches[1]);
    echo "Duplicate words found: " . implode(', ', $duplicates);
} else {
    echo "No duplicate words found.";
}