How does the countSmiley function work in the PHP script?

The countSmiley function in the PHP script works by taking an array of strings as input and counting the number of valid smiley faces within the array. A valid smiley face consists of either a colon or semicolon followed by a dash or tilde, and then either a closing parenthesis or 'D'. To solve this issue, we can use a regular expression to match valid smiley faces within each string in the array and increment a counter for each match.

function countSmiley($arr) {
    $count = 0;
    foreach ($arr as $string) {
        preg_match_all('/[:;][-~]?[)D]/', $string, $matches);
        $count += count($matches[0]);
    }
    return $count;
}

// Example usage
$smileys = [":)", ";D", ":-)", ":~D"];
echo countSmiley($smileys); // Output: 4