📖 Scenario: You are working on a simple text editor tool that needs to replace certain words in a sentence with new words. This is a common task when cleaning or updating text data.
🎯 Goal: Build a PHP script that uses preg_replace to substitute specific words in a given sentence with new words.
📋 What You'll Learn
Create a variable $sentence with the exact text: "The cat sat on the mat."
Create a variable $pattern that matches the word "cat"
Create a variable $replacement with the text "dog"
Use preg_replace with $pattern, $replacement, and $sentence to create a new variable $new_sentence
Print the value of $new_sentence
💡 Why This Matters
🌍 Real World
Text substitution is useful in editing documents, cleaning data, or customizing messages automatically.
💼 Career
Many programming jobs require manipulating text data, and knowing how to use regular expressions with functions like <code>preg_replace</code> is a valuable skill.
Progress0 / 4 steps
1
DATA SETUP: Create the initial sentence
Create a variable called $sentence and set it to the string "The cat sat on the mat." exactly.
PHP
Hint
Use double quotes to create the string exactly as shown.
2
CONFIGURATION: Define the pattern and replacement
Create a variable called $pattern and set it to the regex pattern that matches the word "cat" exactly. Then create a variable called $replacement and set it to the string "dog".
PHP
Hint
Remember to put the pattern between slashes / for regex in PHP.
3
CORE LOGIC: Use preg_replace to substitute the word
Use preg_replace with $pattern, $replacement, and $sentence to create a new variable called $new_sentence.
PHP
Hint
Use the syntax: preg_replace(pattern, replacement, subject).
4
OUTPUT: Print the new sentence
Write a print statement to display the value of $new_sentence.
PHP
Hint
Use print($new_sentence); to show the result.
Practice
(1/5)
1. What does the PHP function preg_replace do?
easy
A. It splits a string into an array based on a pattern.
B. It counts how many times a pattern appears in a string.
C. It finds text matching a pattern and replaces it with new text.
D. It checks if a string matches a pattern and returns true or false.
Solution
Step 1: Understand the purpose of preg_replace
The function preg_replace searches a string for parts that match a pattern and replaces those parts with new text.
Step 2: Compare with other functions
Counting matches or splitting strings are done by other functions like preg_match_all or preg_split, not preg_replace.
Final Answer:
It finds text matching a pattern and replaces it with new text. -> Option C
Quick Check:
preg_replace replaces matched text [OK]
Hint: Remember: replace means find and change text [OK]
Common Mistakes:
Confusing preg_replace with preg_match
Thinking preg_replace counts matches
Mixing preg_replace with string splitting functions
2. Which of the following is the correct syntax to replace all digits with '#' in PHP using preg_replace?
easy
A. preg_replace('/\D/', '#', $text);
B. preg_replace('/d/', '#', $text);
C. preg_replace('/[0-9]+/', '#', $text);
D. preg_replace('/\d/', '#', $text);
Solution
Step 1: Identify the pattern for digits
The pattern '\d' matches any single digit (0-9). In PHP single-quoted strings, it is written as '/\d/'.
Step 2: Check other options
B uses '/d/', which matches the literal letter 'd'. C uses '/[0-9]+/', which matches one or more consecutive digits, replacing the entire group with a single '#'. D uses '/\D/', which matches non-digits.
Final Answer:
preg_replace('/\d/', '#', $text); -> Option D
Quick Check:
Use '\d' to match digits [OK]
Hint: Use '\d' to match digits in regex [OK]
Common Mistakes:
Forgetting to escape backslash in PHP strings
Using 'd' instead of '\d' for digits
Confusing '\d' with '\D' (non-digits)
3. What will be the output of the following PHP code?
A. The limit parameter should be the third argument, not the fourth.
B. The replacement value must be a string, not an integer.
C. The pattern should be enclosed in double quotes, not single quotes.
D. preg_replace cannot limit replacements; the code is correct.
Solution
Step 1: Check preg_replace argument order
The arguments are: pattern, replacement, subject, limit. The limit is correctly the fourth argument.
Step 2: Check replacement type
The replacement should be a string. Using integer 1 will be converted to string '1' but is not recommended and can cause confusion.
Step 3: Check other options
Pattern can be in single quotes. preg_replace supports limit parameter.
Final Answer:
The replacement value must be a string, not an integer. -> Option B
Quick Check:
Replacement should be string [OK]
Hint: Always use string for replacement in preg_replace [OK]
Common Mistakes:
Passing integer instead of string as replacement
Misplacing the limit parameter
Thinking preg_replace can't limit replacements
5. You want to replace only the first two occurrences of the word 'apple' with 'orange' in the string 'apple banana apple apple grape'. Which preg_replace call achieves this?
hard
A. preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 2);
B. preg_replace('/apple/', 'orange', 'apple banana apple apple grape');
C. preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 3);
D. preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 1);
Solution
Step 1: Understand the limit parameter in preg_replace
The fourth argument limits how many replacements happen. To replace only first two 'apple', limit should be 2.
Step 2: Check each option's limit
preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 2); uses limit 2, so only first two 'apple' replaced. preg_replace('/apple/', 'orange', 'apple banana apple apple grape'); replaces all. preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 3); replaces first three. preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 1); replaces only first one.
Final Answer:
preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 2); -> Option A
Quick Check:
Limit 2 replaces first two matches [OK]
Hint: Use limit parameter to control replacements count [OK]
Common Mistakes:
Omitting limit to replace all occurrences
Setting wrong limit number
Confusing order of arguments
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.