Preg_replace helps you find parts of text that match a pattern and replace them with new text. It is useful when you want to change or clean up text automatically.
Preg_replace for substitution in PHP
<?php mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) ?>
$pattern is the regular expression pattern to find.
$replacement is the text to replace the matched parts.
$subject is the text where the search and replace happens.
$limit controls how many replacements to make (default is all).
<?php $text = "Hello 123, call me at 555-1234."; $new_text = preg_replace('/\d+/', 'NUMBER', $text); echo $new_text; ?>
<?php $text = "abc def ghi"; $new_text = preg_replace('/def/', 'xyz', $text, 1); echo $new_text; ?>
<?php $text = "No numbers here!"; $new_text = preg_replace('/\d+/', 'NUM', $text); echo $new_text; ?>
This program finds phone numbers in the text and replaces them with the word '[PHONE]'. It prints the text before and after the change.
<?php // Original text with phone numbers $original_text = "Contact us at 123-456-7890 or 987-654-3210."; // Show original text echo "Before replacement:\n" . $original_text . "\n"; // Replace phone numbers with [PHONE] $pattern = '/\d{3}-\d{3}-\d{4}/'; $replacement = '[PHONE]'; $modified_text = preg_replace($pattern, $replacement, $original_text); // Show modified text echo "After replacement:\n" . $modified_text . "\n"; ?>
Time complexity depends on the length of the text and complexity of the pattern, usually O(n) where n is text length.
Space complexity is O(n) because a new string is created with replacements.
Common mistake: forgetting to escape special characters in the pattern (like \d for digits).
Use preg_replace when you need powerful pattern matching. For simple fixed string replacements, str_replace is faster.
preg_replace finds text matching a pattern and replaces it.
You can control how many replacements happen with the limit parameter.
It is useful for cleaning or formatting text automatically.