Concept of the preg_replace()
Function
The preg_replace()
function uses regular expressions to search for patterns within a string and replace them with other text.
$input = 'Hello, PHP!';
$pattern = '/Hello/'; // Regular expression to match "Hello"
$replacement = 'Hi'; // Replace "Hello" with "Hi"
$output = preg_replace($pattern, $replacement, $input);
echo "Original input: $input"; // Output: "Original input: Hello, PHP!"
echo "Output: $output"; // Output: "Output: Hi, PHP!"
- If you want to match an exact string rather than a pattern, consider using the
str_replace()
function instead. - To search for a pattern in a string without replacing it, use the
preg_match()
function.
Syntax
preg_replace(
string|array $pattern,
string|array $replacement,
string|array $subject,
int $limit = -1,
int &$count = null
): string|array|null
// preg_replace(regex pattern, replacement, subject[, limit[, count]]);
Parameters
$pattern |
Required. Specifies the regular expression pattern to search for.
Can be a string or an array of strings. |
---|---|
$replacement |
Required. Specifies the replacement string or an array of replacement strings for each match found. |
$subject |
Required. The input string or an array of strings to search and replace within.
This is where the pattern is applied and replacements are made. |
$limit |
Optional. Sets the maximum number of replacements to perform.
Default is -1 , which means all matches will be replaced. |
$count |
Optional. A variable that will be populated with the number of replacements performed.
Default is null . Passed by reference. |
Return Values
The preg_replace()
function returns the modified string or array after performing the replacements.
It searches for matches based on the regular expression pattern and returns a new string or array with the matched parts replaced.
Practical Examples
The following examples demonstrate how the preg_replace()
function behaves in various scenarios.
Basic Usage
$original_string = 'Hello, world! Hello, PHP! Hello, universe!';
$pattern = '/Hello/';
$replacement = 'Hi';
$new_string = preg_replace($pattern, $replacement, $original_string);
echo $new_string; // Output: 'Hi, world! Hi, PHP! Hi, universe!'
In this example, the preg_replace()
function replaces all instances of "Hello" with "Hi" and stores the result in the $new_string
variable. The modified string is then printed using echo
.
The function returns a new string with the specified replacements, leaving the original string unchanged.
Replacing Multiple Patterns Using Arrays
$original_string = 'Apples are red. Bananas are yellow. Apples and bananas are delicious.';
$search = ['/Apples/', '/Bananas/']; // Regex patterns as an array
$replace = ['Oranges', 'Grapes']; // Corresponding replacements
$new_string = preg_replace($search, $replace, $original_string);
echo $new_string;
// Output: 'Oranges are red. Grapes are yellow. Oranges and bananas are delicious.'
This example shows how you can use arrays to replace multiple patterns in a string.
Each pattern in the $search
array is replaced with the corresponding value in the $replace
array.
Using the $count
Parameter
The $count
parameter can be useful for determining how many times a specific pattern appears in a string. This allows you to count the number of occurrences while performing the replacements.
For example, suppose you want to count how many times the word "PHP" appears in a string.
$original_string = 'PHP is a popular scripting language. PHP stands for PHP: Hypertext Preprocessor.';
$pattern = '/PHP/';
$replacement = 'PHP';
$count = 0;
$new_string = preg_replace($pattern, $replacement, $original_string, -1, $count);
echo $new_string;
// Output: 'PHP is a popular scripting language. PHP stands for PHP: Hypertext Preprocessor.'
echo "The word 'PHP' appeared {$count} times.";
// Output: The word 'PHP' appeared 3 times.
In this case, even though the replacement string is the same as the matched pattern,
preg_replace()
still performs the operation and counts how many replacements were made.
The $count
variable is updated by reference to reflect the total number of matches.
Limiting the Number of Replacements
You can use the $limit
parameter to restrict how many times a pattern is replaced in the string.
This is useful when you only want to replace the first few occurrences of a pattern.
$input = 'One, one, one, one';
$pattern = '/one/i'; // 'i' flag makes the match case-insensitive
$replacement = 'ONE';
$output = preg_replace($pattern, $replacement, $input, 2);
echo $output;
// Output: 'ONE, ONE, one, one'
In this example, only the first two matches of "one" are replaced with "ONE".
The i
flag in the pattern makes the matching case-insensitive,
so it matches both "One" and "one". The $limit
parameter restricts the replacements to 2
.