0
0
PHPprogramming~20 mins

Why regex is needed in PHP - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Regex Master in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use regex in PHP for text searching?

Imagine you want to find all email addresses in a long text. Why is regex useful in PHP for this task?

ARegex converts text into numbers for calculations.
BRegex lets you search complex patterns like emails easily in text.
CRegex automatically fixes spelling mistakes in the text.
DRegex is used to create images from text.
Attempts:
2 left
💡 Hint

Think about how you find a pattern, not just a word.

Predict Output
intermediate
2:00remaining
What is the output of this PHP regex code?

Look at this PHP code that uses regex to check if a string contains digits:

$text = 'Hello123';
if (preg_match('/\d+/', $text)) {
    echo 'Digits found';
} else {
    echo 'No digits';
}

What will it print?

ADigits found
BEmpty output
CSyntax error
DNo digits
Attempts:
2 left
💡 Hint

\d+ means one or more digits.

Predict Output
advanced
2:00remaining
What does this PHP regex code output?

Consider this PHP code that extracts all words starting with 'a' or 'A':

$text = 'Apple and apricot are awesome';
preg_match_all('/\b[aA]\w*/', $text, $matches);
print_r($matches[0]);

What is the output?

AArray ( [0] => Apple )
BArray ( [0] => Apple [1] => apricot [2] => are [3] => awesome )
CArray ( [0] => Apple [1] => and [2] => apricot [3] => are [4] => awesome )
DArray ( )
Attempts:
2 left
💡 Hint

\b means word boundary, [aA] matches 'a' or 'A', \w* matches letters after.

🧠 Conceptual
advanced
2:00remaining
Why is regex preferred over string functions for pattern matching in PHP?

Why would a PHP developer choose regex instead of simple string functions like strpos or strstr for pattern matching?

ARegex can match complex patterns and conditions, not just fixed strings.
BRegex runs faster than any string function always.
CRegex automatically translates text to other languages.
DRegex is easier to read and write than string functions.
Attempts:
2 left
💡 Hint

Think about matching patterns like phone numbers or emails.

Predict Output
expert
2:00remaining
What error does this PHP regex code raise?

Look at this PHP code snippet:

$pattern = '/(abc/';
$text = 'abcdef';
preg_match($pattern, $text, $matches);
print_r($matches);

What error will this code produce?

AParse error: syntax error, unexpected '/'
BFatal error: Undefined variable $matches
CNo output, empty array printed
DWarning: preg_match(): Compilation failed: missing ) at offset 4
Attempts:
2 left
💡 Hint

Check if the regex pattern is correctly closed.