Complete the code to check if the string contains the word 'apple'.
<?php $string = "I like apples."; if (preg_match([1], $string)) { echo "Found apple!"; } ?>
The preg_match function requires a pattern enclosed in delimiters like slashes. So "/apple/" is the correct regex pattern.
Complete the code to replace all digits in the string with '#'.
<?php $text = "My phone is 123-456-7890."; $result = preg_replace([1], '#', $text); echo $result; ?>
The regex /\d/ matches any digit. So it replaces all digits with '#'.
Fix the error in the regex pattern to match an email address.
<?php $email = "user@example.com"; if (preg_match([1], $email)) { echo "Valid email."; } else { echo "Invalid email."; } ?>
The regex pattern must be enclosed in delimiters like slashes. Option B correctly uses slashes and anchors.
Fill both blanks to create a dictionary of words and their lengths for words longer than 3 characters.
<?php $words = ['cat', 'elephant', 'dog', 'horse']; $lengths = array_filter(array_map(function($word) { return strlen($word); }, $words), function($word) { return $word [1] 3; }); print_r($lengths); ?>
The code filters words with length greater than 3, so the operator should be >.
Fill all three blanks to create an associative array of uppercase words and their lengths for words longer than 4 characters.
<?php $words = ['apple', 'bat', 'carrot', 'dog']; $result = array_filter(array_combine(array_map(function($word) { return [1]; }, $words), array_map(function($word) { return [2]; }, $words)), function($length) { return $length [3] 4; }); print_r($result); ?>
strtolower instead of strtoupper.The keys are uppercase words (strtoupper($word)), values are lengths (strlen($word)), and filter keeps lengths greater than 4 (>).