Complete the code to replace all occurrences of 'apple' with 'orange' in the string.
<?php $text = "I like apple pie."; $newText = str_replace([1], "orange", $text); echo $newText; ?>
The str_replace function replaces all occurrences of the first string with the second string. Here, we want to replace "apple" with "orange".
Complete the code to replace the first occurrence of 'cat' with 'dog' in the string.
<?php $text = "The cat sat on the cat mat."; $newText = preg_replace('/[1]/', "dog", $text, 1); echo $newText; ?>
The preg_replace function uses a pattern to find matches. Here, the pattern is '/cat/' to find the word 'cat'. The fourth argument '1' limits replacement to the first match.
Fix the error in the code to replace 'blue' with 'red' in the string.
<?php $color = "blue"; $text = "The sky is blue."; $newText = str_replace([1], "red", $text); echo $newText; ?>
The variable $color holds the string 'blue'. To use it in str_replace, we must pass the variable name with the dollar sign.
Fill both blanks to create a dictionary of words and their replacements, then replace them in the text.
<?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; ?>
The array keys are the words to find, and the values are the words to replace them with. Here, "cat" is replaced with "dog" and "dog" is replaced with "cat".
Fill all three blanks to replace all vowels with '*' in the string using str_replace.
<?php $text = "Hello World!"; $vowels = array([1]); $stars = array([2]); $newText = str_replace($vowels, $stars, [3]); echo $newText; ?>
We create an array of vowels to find and an array of stars to replace them. Then we call str_replace with these arrays and the original text.