Bird
Raised Fist0
PHPprogramming~10 mins

Preg_replace for substitution in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Preg_replace for substitution
Input string
↓
Define pattern and replacement
↓
Call preg_replace
↓
Search string for pattern matches
↓
Replace matches with replacement
↓
Return new string with substitutions
The flow shows how preg_replace takes an input string, finds parts matching a pattern, replaces them, and returns the new string.
Execution Sample
PHP
<?php
$input = "Hello 123 World 456";
$output = preg_replace('/\d+/', 'NUM', $input);
echo $output;
?>
This code replaces all groups of digits in the input string with 'NUM'.
Execution Table
StepActionPattern MatchReplacementResulting String
1Start with input stringN/AN/AHello 123 World 456
2Find first match '\d+'Matches '123'Replace with 'NUM'Hello NUM World 456
3Find second match '\d+'Matches '456'Replace with 'NUM'Hello NUM World NUM
4No more matchesN/AN/AHello NUM World NUM
💡 No more digit groups found, substitution complete.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
$input"Hello 123 World 456""Hello 123 World 456""Hello 123 World 456""Hello 123 World 456"
$outputundefined"Hello NUM World 456""Hello NUM World NUM""Hello NUM World NUM"
Key Moments - 3 Insights
Why does preg_replace replace all matches, not just the first?
preg_replace by default replaces all matches in the string, as shown in execution_table rows 2 and 3 where both '123' and '456' are replaced.
What does the pattern '/\d+/' mean?
It means 'one or more digits'. This is why '123' and '456' are matched and replaced, as seen in execution_table rows 2 and 3.
Why is the original $input variable unchanged?
preg_replace returns a new string with replacements; it does not modify the original string, as shown in variable_tracker where $input stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the string after the first replacement?
A"Hello NUM World NUM"
B"Hello NUM World 456"
C"Hello 123 World NUM"
D"Hello 123 World 456"
💡 Hint
Check execution_table row 2 under 'Resulting String'.
At which step does preg_replace stop finding matches?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look at execution_table row 4 where no more matches are found.
If the pattern was changed to '/World/', what would be the output after replacement?
A"Hello 123 NUM 456"
B"654 MUN 321 olleH"
CHello 123 NUM 456"
D"Hello 123 NUM 456
💡 Hint
Replacing 'World' with 'NUM' changes only that word; digits remain unchanged.
Concept Snapshot
preg_replace(pattern, replacement, string) searches the string for parts matching the pattern.
It replaces all matches with the replacement text.
Returns a new string; original string stays unchanged.
Patterns use regular expressions, like '/\d+/' for digits.
Useful for flexible text substitutions.
Full Transcript
This visual trace shows how PHP's preg_replace function works step-by-step. Starting with the input string 'Hello 123 World 456', it looks for parts matching the pattern '/\d+/', which means one or more digits. It finds '123' first and replaces it with 'NUM', then finds '456' and replaces it too. The original string remains unchanged, and the function returns a new string with all digit groups replaced by 'NUM'. The process stops when no more matches are found. This helps beginners see how preg_replace scans and replaces all matches, not just the first, and how the pattern controls what is matched.

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

  1. 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.
  2. 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.
  3. Final Answer:

    It finds text matching a pattern and replaces it with new text. -> Option C
  4. 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

  1. 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/'.
  2. 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.
  3. Final Answer:

    preg_replace('/\d/', '#', $text); -> Option D
  4. 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?
$text = "Hello 123 World";
$result = preg_replace('/\d+/', 'NUM', $text);
echo $result;
medium
A. Hello NUM World
B. Hello 123 World
C. NUM NUM NUM World
D. Hello NUM123 World

Solution

  1. Step 1: Understand the regex pattern '/\d+/'

    The pattern '\d+' matches one or more digits in a row. In the string, '123' matches this pattern.
  2. Step 2: Apply preg_replace to the string

    The matched digits '123' are replaced by 'NUM'. So the string becomes 'Hello NUM World'.
  3. Final Answer:

    Hello NUM World -> Option A
  4. Quick Check:

    Digits replaced by 'NUM' = Hello NUM World [OK]
Hint: Look for digit groups replaced by 'NUM' [OK]
Common Mistakes:
  • Thinking only single digits replaced separately
  • Expecting original digits to remain
  • Confusing pattern with non-digit matching
4. Identify the error in this PHP code snippet:
$text = "abc123def";
$result = preg_replace('/[a-z]/', 1, $text, 2);
echo $result;
medium
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

  1. Step 1: Check preg_replace argument order

    The arguments are: pattern, replacement, subject, limit. The limit is correctly the fourth argument.
  2. 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.
  3. Step 3: Check other options

    Pattern can be in single quotes. preg_replace supports limit parameter.
  4. Final Answer:

    The replacement value must be a string, not an integer. -> Option B
  5. 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

  1. 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.
  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.
  3. Final Answer:

    preg_replace('/apple/', 'orange', 'apple banana apple apple grape', 2); -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard