0
0
PHPprogramming~10 mins

String replace functions 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 occurrences of 'apple' with 'orange' in the string.

PHP
<?php
$text = "I like apple pie.";
$newText = str_replace([1], "orange", $text);
echo $newText;
?>
Drag options to blanks, or click blank then click option'
A"pear"
B"banana"
C"apple"
D"grape"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong string to replace.
Not putting the string to find in quotes.
2fill in blank
medium

Complete the code to replace the first occurrence of 'cat' with 'dog' in the string.

PHP
<?php
$text = "The cat sat on the cat mat.";
$newText = preg_replace('/[1]/', "dog", $text, 1);
echo $newText;
?>
Drag options to blanks, or click blank then click option'
Adog
Bcat
Attempts:
3 left
💡 Hint
Common Mistakes
Using the replacement string as the pattern.
Forgetting the slashes around the pattern.
3fill in blank
hard

Fix the error in the code to replace 'blue' with 'red' in the string.

PHP
<?php
$color = "blue";
$text = "The sky is blue.";
$newText = str_replace([1], "red", $text);
echo $newText;
?>
Drag options to blanks, or click blank then click option'
Ablue
Bcolor
C"color"
D$color
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the dollar sign for variables.
Passing the variable name as a string.
4fill in blank
hard

Fill both blanks to create a dictionary of words and their replacements, then replace them in the text.

PHP
<?php
$text = "I have a cat and a dog.";
$replacements = array([1] => "dog", [2] => "cat");
$newText = str_replace(array_keys($replacements), array_values($replacements), $text);
echo $newText;
?>
Drag options to blanks, or click blank then click option'
A"cat"
B"dog"
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping keys and values.
Not using quotes around the words.
5fill in blank
hard

Fill all three blanks to replace all vowels with '*' in the string using str_replace.

PHP
<?php
$text = "Hello World!";
$vowels = array([1]);
$stars = array([2]);
$newText = str_replace($vowels, $stars, [3]);
echo $newText;
?>
Drag options to blanks, or click blank then click option'
A"a", "e", "i", "o", "u"
B"*", "*", "*", "*", "*"
C$text
D"aeiou"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of an array for vowels or stars.
Forgetting the dollar sign for variables.