PHP Preg_Replace with Advanced Examples

What is PHP Preg_Replace?

The PHP preg_replace() function is a built-in language function and is useful for handling strings in an array.

It works with strings by giving back a string or an array of strings with substrings for all matches of a pattern or list of patterns found in the input.

Additionally, we can use the preg_replace function in here easy ways:

  1. The first way of using the function is with one pattern and one string replacement. It replaces matches in the pattern with the replacement string.

  1. Second, we can use preg_replace() with a collection of patterns along with a replacement string. It can also replace any similar patterns with the replacement string.

  1. The third option is to employ a set of patterns and replacement strings. Each pattern’s matches are replaced with the replacement string located at the same index in the replacement array. If no match is visible at that point, the program will return an empty string.

The method of replacing strings may include a backreference of the type \n or $n, where n is the group index in the pattern.

In the returned string, instances of \n and $n will be replaced with the substring that was matched by the group, or the entire expression if \0 or $0 is used.

Important Note:

You should understand that, for each string input, PHP preg_replace evaluates the patterns in the order that they are already in.

Why PHP preg_replace() is Important?

The preg_replace() method is important since it assists with searching and changing text using regular expressions.

This method operates on either a single string or several string elements present inside the array index values.

Furthermore, the function is similar to preg _match(), except that when a pattern match is done on a string, the string element(s) are replaced with the specified text.

This is a useful regular expression for changing string content in the PHP programming language.

PHP preg_replace – Description

To describe the preg_replace function, let us have a simple implementation of using it in a program.

preg_replace(
    string|array $pattern,
    string|array $replacement,
    string|array $subject,
    int $limit = -1,
    int &$count = null
): string|array|null

This sample shows how we use the function in a program.

Specifically, this gives you the proper syntax of the PHP preg_replace() function and we will elaborate on its definition in the discussions below.

Parameters

The syntax of the preg_replace() function gets the following parameters.

Pattern

The pattern is the first parameter that the function takes in implementing the function.

This parameter designates a pattern that the function should follow.

Moreover, this parameter can either be a string or an array of strings. Some of the PCRE Modifiers are made available in this parameter.

Replacement

The next parameter that PHP preg_replace takes is the replacement parameter.

This is the string or the array values to replace and considers the following statement upon implementation:

  • First, if the replacement parameter is a string and the pattern parameter is an array, the string will have it substitute for each pattern.

  • Second, if both the pattern and replacement parameters are arrays, each pattern turns to its corresponding replacement.

  • Third, if the replacement array has fewer elements than the pattern array, the empty string will replace any extra patterns. 

In addition, when the deprecated e modifier is used, this function escapes characters such as ‘'"\ and NULL in the strings that replace the backreferences.

This ensures that backreference usage with single or double quotes does not result in syntactic issues.

Therefore, you have to make sure that you are familiar with PHP’s string syntax to know exactly how the string function will work.

Subject

Next is the subject parameter, which is the string or an array of strings to search and replace.

During implementation, the following scenario also applies:

  • If the subject is an array, the search and replace operation is executed on each entry, and the return value is also an array.
  • If the subject array is associative, the returned value will preserve the keys.

Limit

The limit parameter is optional in the case of the PHP preg_replace() function.

This parameter indicates the maximum replacements for each pattern in the subject string parameter.

When there’s no limit indication, the function will implement its default, which is -1, meaning there’s no limit.

Count

This parameter will indicate how many replacements were done upon the process execution.

Return values

The PHP preg_replace() function returns an array if the subject parameter is an array.

But the parameter is a string, the function returns a string.

If there are matches, the new subject will be returned.

If there are no matches, the old subject will be returned, or null if there was an error.

Errors and Exceptions

The “e” modifier is used to display errors in the function, and an E_WARNING is displayed in this case.

Example Program using Backreferences followed by Numeric Literals

Example Code:

<?php
$string = 'October 14, 2022';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1} 1, $3';
echo preg_replace($pattern, $replacement, $string);
?>

Output:

October 1, 2022

Example Program using Indexed Arrays with preg_replace()

Example Code:

<?php
$string = 'The tiger runs faster than other animals.';
$patterns = array();
$patterns[0] = '/tiger/';
$patterns[1] = '/runs/';
$patterns[2] = '/faster/';

$replacements = array();
$replacements[0] = 'lion';
$replacements[1] = 'roars';
$replacements[2] = 'louder';
echo preg_replace($patterns, $replacements, $string);
?>

Output:

The lion roars louder than other animals.

Example Program for Replacing Several Values

Example Code

<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                   '/^\s*{(\w+)}\s*=/');
$replacements = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replacements, '{Date} = 2022-10-01');
?>

Output:

$Date = 10/01/2022

Example Program for Strip Whitespace

Example Code:

<?php
$string = 'Hello   World!';
$string = preg_replace('/\s\s+/', ' ', $string);
echo $string;
?>

Output:

Hello World!

Example program using the count parameter

Example Code:

<?php
$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '-', 'As to', -1 , $count);
echo $count; //3
?>

Output:

As-to1

Conclusion

The topic now completes all the discussion needed to understand the PHP preg_replace function.

It also provided various examples that clarify the different uses and advantages of the function.

If you want to further discuss this information, tap us through the comments. Have a good day!

Leave a Comment