0
0
PHPprogramming~10 mins

Preg_replace for substitution in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to replace all digits with a dash using preg_replace.

PHP
<?php
$text = "Call me at 123-456-7890.";
$result = preg_replace([1], '-', $text);
echo $result;
?>
Drag options to blanks, or click blank then click option'
A"/\s/"
B"/\w/"
C"/\d/"
D"/\D/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using \w matches letters and digits, not just digits.
Using \s matches spaces, not digits.
Using \D matches non-digits, which is the opposite.
2fill in blank
medium

Complete the code to replace all vowels with '*' using preg_replace.

PHP
<?php
$text = "Hello World!";
$result = preg_replace([1], '*', $text);
echo $result;
?>
Drag options to blanks, or click blank then click option'
A"/\s/"
B"/[aeiou]/i"
C"/[bcdfg]/i"
D"/[0-9]/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using digits or consonants in the pattern instead of vowels.
Forgetting the 'i' modifier to match uppercase vowels.
3fill in blank
hard

Fix the error in the code to replace all spaces with underscores using preg_replace.

PHP
<?php
$text = "Replace spaces here.";
$result = preg_replace([1], '_', $text);
echo $result;
?>
Drag options to blanks, or click blank then click option'
A"/\s/"
B"/ /"
C"/\S/"
D"/\d/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using \S matches non-whitespace, which is incorrect here.
Using \d matches digits, not spaces.
4fill in blank
hard

Fill both blanks to replace all words starting with 'a' or 'A' with 'word' using preg_replace.

PHP
<?php
$text = "An apple a day keeps the doctor away.";
$result = preg_replace([1], [2], $text);
echo $result;
?>
Drag options to blanks, or click blank then click option'
A"/\b[aA]\w*/"
B"/\d+/"
C'word'
D'fruit'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect patterns that don't match word boundaries.
Forgetting to quote the replacement string.
5fill in blank
hard

Fill all three blanks to replace all digits with '#' only if they are at the start of the string using preg_replace.

PHP
<?php
$text = "123abc456";
$result = preg_replace([1], [2], $text, [3]);
echo $result;
?>
Drag options to blanks, or click blank then click option'
A"/^\d+/"
B'#'
C1
D"/\d+/"
Attempts:
3 left
💡 Hint
Common Mistakes
Using pattern without ^ matches digits anywhere.
Forgetting to quote the replacement string.
Not setting the limit to 1 causes all digits to be replaced.