Recall & Review
beginner
What does the
preg_replace function do in PHP?preg_replace searches a string for matches to a regular expression pattern and replaces them with a specified replacement string.
Click to reveal answer
beginner
What are the three main parameters of
preg_replace?- pattern: The regex pattern to search for.
- replacement: The string to replace matches with.
- subject: The input string to search and replace in.
Click to reveal answer
beginner
How do you use
preg_replace to replace all digits in a string with a dash (-)?preg_replace('/\d/', '-', 'Phone: 123-456'); // Result: 'Phone: --- ---'Click to reveal answer
beginner
What happens if no matches are found when using
preg_replace?The original string is returned unchanged because there is nothing to replace.
Click to reveal answer
intermediate
Can
preg_replace use backreferences in the replacement string? Give an example.<p>Yes. Backreferences let you reuse parts of the matched text in the replacement.</p><pre>preg_replace('/(\w+) (\w+)/', '$2 $1', 'John Doe'); // Result: 'Doe John'</pre>Click to reveal answer
What does
preg_replace('/cat/', 'dog', 'catapult') return?✗ Incorrect
The pattern 'cat' is found at the start of 'catapult' and replaced with 'dog', resulting in 'dogapult'.
Which delimiter is used in the pattern
/\d+/ in preg_replace?✗ Incorrect
The slashes / are the delimiters that mark the start and end of the regex pattern.
What will
preg_replace('/(\w+) (\w+)/', '$2 $1', 'Hello World') output?✗ Incorrect
The two words are swapped using backreferences $2 and $1 in the replacement string.
If the pattern does not match anything in the subject, what does
preg_replace return?✗ Incorrect
No matches means no replacements, so the original string is returned unchanged.
Which of these is a valid use of
preg_replace to remove all vowels from a string?✗ Incorrect
Option A uses a regex pattern with character class and case-insensitive flag i to remove vowels.
Explain how
preg_replace works for substituting text in a string.Think about how you find and replace words using a pattern.
You got /4 concepts.
Describe how backreferences can be used in the replacement string of
preg_replace.Imagine swapping parts of a matched phrase.
You got /4 concepts.