0
0
PHPprogramming~20 mins

Preg_match for pattern matching in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Preg_match Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this preg_match code?

Consider the following PHP code snippet using preg_match. What will it output?

PHP
<?php
$pattern = '/^hello/';
$subject = 'hello world';
if (preg_match($pattern, $subject)) {
    echo 'Match found';
} else {
    echo 'No match';
}
?>
AMatch foundhello
BNo match
CWarning: preg_match(): Unknown modifier '^'
DMatch found
Attempts:
2 left
💡 Hint

Check if the pattern matches the start of the string.

Predict Output
intermediate
2:00remaining
What does this preg_match return?

What will be the output of this PHP code?

PHP
<?php
$pattern = '/\d+/';
$subject = 'abc123xyz';
if (preg_match($pattern, $subject, $matches)) {
    echo $matches[0];
} else {
    echo 'No digits';
}
?>
AWarning: preg_match(): Unknown modifier '\'
B123
CNo digits
Dabc123xyz
Attempts:
2 left
💡 Hint

Look for digits in the string.

Predict Output
advanced
2:00remaining
What is the output of this preg_match with capturing groups?

Analyze this PHP code and determine its output.

PHP
<?php
$pattern = '/(foo)(bar)?/';
$subject = 'foobar';
if (preg_match($pattern, $subject, $matches)) {
    echo count($matches);
} else {
    echo 'No match';
}
?>
A3
B2
C1
DNo match
Attempts:
2 left
💡 Hint

Count how many capturing groups matched.

Predict Output
advanced
2:00remaining
What error does this preg_match code produce?

What error will this PHP code produce when run?

PHP
<?php
$pattern = '/[a-z/';
$subject = 'abc';
preg_match($pattern, $subject);
?>
AWarning: preg_match(): Compilation failed: missing terminating ] for character class
BNo output, runs fine
CFatal error: Uncaught Error: Call to undefined function preg_match()
DParse error: syntax error, unexpected '/'
Attempts:
2 left
💡 Hint

Check the regex pattern syntax carefully.

🧠 Conceptual
expert
2:00remaining
How many matches does preg_match find here?

Given this PHP code, how many matches will preg_match find?

PHP
<?php
$pattern = '/cat/';
$subject = 'cat concatenate catapult';
$result = preg_match($pattern, $subject, $matches);
echo $result;
?>
A0
B2
C1
D3
Attempts:
2 left
💡 Hint

Remember that preg_match finds only the first match.