Consider the following PHP code snippet using preg_match. What will it output?
<?php $pattern = '/^hello/'; $subject = 'hello world'; if (preg_match($pattern, $subject)) { echo 'Match found'; } else { echo 'No match'; } ?>
Check if the pattern matches the start of the string.
The pattern /^hello/ matches strings starting with 'hello'. The subject string starts with 'hello', so preg_match returns true and 'Match found' is printed.
What will be the output of this PHP code?
<?php $pattern = '/\d+/'; $subject = 'abc123xyz'; if (preg_match($pattern, $subject, $matches)) { echo $matches[0]; } else { echo 'No digits'; } ?>
Look for digits in the string.
The pattern /\d+/ matches one or more digits. The subject contains '123', so preg_match finds it and stores it in $matches[0].
Analyze this PHP code and determine its output.
<?php $pattern = '/(foo)(bar)?/'; $subject = 'foobar'; if (preg_match($pattern, $subject, $matches)) { echo count($matches); } else { echo 'No match'; } ?>
Count how many capturing groups matched.
The pattern has two capturing groups: (foo) and (bar)?. The subject 'foobar' matches both groups, so $matches has 3 elements: full match, group 1, and group 2.
What error will this PHP code produce when run?
<?php $pattern = '/[a-z/'; $subject = 'abc'; preg_match($pattern, $subject); ?>
Check the regex pattern syntax carefully.
The pattern /[a-z/ is missing the closing bracket for the character class, causing a compilation error in preg_match.
Given this PHP code, how many matches will preg_match find?
<?php $pattern = '/cat/'; $subject = 'cat concatenate catapult'; $result = preg_match($pattern, $subject, $matches); echo $result; ?>
Remember that preg_match finds only the first match.
preg_match returns 1 if it finds at least one match, but it only finds the first match, so the result is 1.