0
0
PHPprogramming~5 mins

Preg_replace for substitution in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Acatapult
Bcatdog
Cdog
Ddogapult
Which delimiter is used in the pattern /\d+/ in preg_replace?
A#
B/
C~
D%
What will preg_replace('/(\w+) (\w+)/', '$2 $1', 'Hello World') output?
A$2 $1
BHello World
CWorld Hello
DHello
If the pattern does not match anything in the subject, what does preg_replace return?
AThe original subject string
BNULL
CAn error
DAn empty string
Which of these is a valid use of preg_replace to remove all vowels from a string?
Apreg_replace('/[aeiou]/i', '', 'Hello')
Bpreg_replace('aeiou', '', 'Hello')
Cpreg_replace('/aeiou/', '', 'Hello')
Dpreg_replace('/[aeiou]/', ' ', 'Hello')
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.