Challenge - 5 Problems
Preg_replace Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this preg_replace code?
Consider the following PHP code snippet using
preg_replace. What will be printed?PHP
<?php $text = "The rain in Spain falls mainly in the plain."; $result = preg_replace('/ain/', 'ane', $text); echo $result; ?>
Attempts:
2 left
💡 Hint
Remember that preg_replace replaces all matches of the pattern.
✗ Incorrect
The pattern '/ain/' matches every occurrence of 'ain' in the string. Each 'ain' is replaced by 'ane', so all 'ain' substrings become 'ane'.
❓ Predict Output
intermediate2:00remaining
What does this preg_replace code output?
What will be the output of this PHP code using
preg_replace with a capturing group?PHP
<?php $input = "abc123def456"; $output = preg_replace('/(\d+)/', '<num>$1</num>', $input); echo $output; ?>
Attempts:
2 left
💡 Hint
The pattern matches one or more digits and replaces each match with the digits wrapped in tags.
✗ Incorrect
The regex '(\d+)' matches sequences of digits. Each sequence is replaced by the same digits wrapped in and tags. So '123' and '456' are replaced separately.
❓ Predict Output
advanced2:00remaining
What is the output of this preg_replace with limit?
What will this PHP code print when using preg_replace with a limit of 1 replacement?
PHP
<?php $str = "one two three two one"; $result = preg_replace('/two/', '2', $str, 1); echo $result; ?>
Attempts:
2 left
💡 Hint
The limit parameter controls how many replacements are made.
✗ Incorrect
The pattern '/two/' matches 'two'. With limit 1, only the first occurrence is replaced by '2'. The rest remain unchanged.
❓ Predict Output
advanced2:00remaining
What error does this preg_replace code produce?
What error will this PHP code produce when run?
PHP
<?php $text = "hello world"; $result = preg_replace('/(world/', 'earth', $text); echo $result; ?>
Attempts:
2 left
💡 Hint
Check the regex pattern for syntax errors.
✗ Incorrect
The regex pattern '/(world/' is missing a closing parenthesis, causing a compilation error in preg_replace.
🧠 Conceptual
expert2:00remaining
How many replacements are made by this preg_replace call?
Given the PHP code below, how many replacements will preg_replace perform?
PHP
<?php $str = "aaa bbb aaa bbb aaa"; $replaced = preg_replace('/aaa/', 'zzz', $str, -1, $count); echo $count; ?>
Attempts:
2 left
💡 Hint
The fourth argument is the limit, and the fifth argument stores the count of replacements.
✗ Incorrect
The pattern '/aaa/' matches 'aaa' three times in the string. The limit -1 means no limit, so all matches are replaced. The variable $count holds the number of replacements, which is 3.