0
0
PHPprogramming~20 mins

Preg_replace for substitution in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Preg_replace Master
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_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;
?>
AThe rane in Spane falls manely in the plane.
BThe rain in Spain falls mainly in the plain.
CThe rane in Spain falls mainly in the plain.
DThe rane in Spain falls manely in the plain.
Attempts:
2 left
💡 Hint
Remember that preg_replace replaces all matches of the pattern.
Predict Output
intermediate
2: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;
?>
Aabc<num>123def456</num>
Babc<num>123</num>def<num>456</num>
Cabc123def456
Dabc<num></num>def<num></num>
Attempts:
2 left
💡 Hint
The pattern matches one or more digits and replaces each match with the digits wrapped in tags.
Predict Output
advanced
2: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;
?>
Aone 2 three two one
Bone 2 three 2 one
Cone 2 three
Done two three two one
Attempts:
2 left
💡 Hint
The limit parameter controls how many replacements are made.
Predict Output
advanced
2: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;
?>
Ahello world
Bhello earth
CWarning: preg_replace(): Compilation failed: missing ) at offset 7
DFatal error: Uncaught Error: Call to undefined function preg_replace()
Attempts:
2 left
💡 Hint
Check the regex pattern for syntax errors.
🧠 Conceptual
expert
2: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;
?>
A5
B1
C0
D3
Attempts:
2 left
💡 Hint
The fourth argument is the limit, and the fifth argument stores the count of replacements.