preg_replace() Function in PHP

The facility to search or replace any particular string in content is essential for almost every application. Manually finding any specific string becomes difficult, and to implement it in a simple way, PHP provides a built-in function. In this tutorial, you will learn about the preg_replace() function of PHP.

The preg_replace() Function

The preg_replace() function, a built-in function in PHP used to check strings using a regular expression to find and replace a string in content.

Syntax:
preg_replace( pattern_lookup, replacement_string, subject, limit, count )

Parameters

This function can accept up to five different parameters where each of them has its unique characteristics.

  • The first parameter, "pattern_lookup", is a mandatory parameter that will hold the string part to find the content. This parameter can be a string or an array of strings.
  • The second parameter, "replacement_string", is another mandatory parameter that holds the string or a collection of arrays with strings for which will be replaced.
  • The third parameter, "subject", holds the string or a collection of arrays with strings for searching and replacing.
  • Here the optional parameter "limit", is used for determining the number of matches that have to occur. Also, when another optional parameter "count", is added, this variable is used to determine the number of replacements to be done.
  • Once the replacement is done, this function will return a modified string. If no match is found, the old string will not change.

The preg_replace() Function Example

Here is a PHP code snippet showing the use of preg_replace() function:

Example
<?php
$String = "Copyright 2016";
$String = preg_replace("([0-9]+)", "2020", $String);
echo $String;
?>
Output
Copyright 2020

In the above example, the year 2016 has been replaced with the year 2020.

Replacing Techniques

Some commonly used pattern matching examples are shown here:

  • preg_replace('/IOS/', 'Apple', $string); #Normal matching and replacment.
  • preg_replace('/IOS/i', 'Apple', $string); #Case-insensitive matching and replacemnt.
  • preg_replace('/\s+/', '', $string); #Strip all the additional whitespace from the string.

Scroll Back to Top