0
0
PHPprogramming~5 mins

Preg_replace for substitution in PHP

Choose your learning style9 modes available
Introduction

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.

You want to replace all phone numbers in a text with a placeholder.
You need to change date formats inside a string.
You want to remove or replace certain words or characters from user input.
You want to add a prefix or suffix to specific words in a sentence.
Syntax
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).

Examples
Replaces all groups of digits with the word 'NUMBER'.
PHP
<?php
$text = "Hello 123, call me at 555-1234.";
$new_text = preg_replace('/\d+/', 'NUMBER', $text);
echo $new_text;
?>
Replaces only the first occurrence of 'def' with 'xyz'.
PHP
<?php
$text = "abc def ghi";
$new_text = preg_replace('/def/', 'xyz', $text, 1);
echo $new_text;
?>
If no match is found, the original text stays the same.
PHP
<?php
$text = "No numbers here!";
$new_text = preg_replace('/\d+/', 'NUM', $text);
echo $new_text;
?>
Sample Program

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
<?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";
?>
OutputSuccess
Important Notes

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.

Summary

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.