PHP preg_replace() function

The preg_replace() function is a built-in function of PHP. It is used to perform a regular expression search and replace.

This function searches for pattern in subject parameter and replaces them with the replacement.

Syntax

snippet
preg_replace (mixed $pattern, mixed $replacement, mixed $subject, int $limit, int $count)

Parameters

This function accepts five parameters, which are described below:

pattern

This parameter can be either a string or an array with strings. It holds the pattern to search in subject parameter.

replacement

It is a string or an array with strings parameter. This parameter replaces the pattern matched in subject parameter. It is a mandatory parameter.

  • If the replacement parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string.
  • If both replacement and pattern parameters are arrays, each pattern will be replaced by the replacement counterpart.
  • If the replacement array consists of fewer elements than the pattern array, any extra pattern will be replaced by an empty string.

subject

The subject parameter can also be either a string or an array of string to search and replace.

If the subject is an array, the search and replacement are performed on every entry of subject, and the returned value will also be an array.

limit

The limit is an optional parameter that specifies the maximum possible replacement for each pattern. The default value of limit is -1, which means no limit.

count

It is an optional parameter. If this parameter is passed, this variable will contain the number of replacements done. This parameter added in PHP 5.1.0.

Return Type

The preg_replace() function returns an array if the subject parameter is an array otherwise it returns a string.

  • After the replacement has done, the modified string will be returned.
  • If any matches do not find, the string will remain unchanged.

Examples

Simple Replacing

snippet
$res = preg_replace('/abc/', 'efg', $string);		#Replace all 'abc' with 'efg'
$res = preg_replace('/abc/i', 'efg', $string);		#Replace with case-insensitive matching
$res = preg_replace('/\s+/', '', $string);		#Strip all whitespace

See the detailed examples to understand the preg_replace() function practically:

Example using backreference followed by numeric literals

snippet
<?php
	$date = 'May 29, 2020';
	$pattern = '/(\w+) (\d+), (\d+)/i';
	$replacement = '${1} 5,$3';
		
	//display the result returned by preg_replace
	echo preg_replace($pattern, $replacement, $date);
?>

Output:

Output
May 5, 2020

Example to strip whitespace

In the below example, preg_replace() removes all extra whitespace from the given string.

snippet
<?php
	$str = 'Camila    Cabello   is    a   Hollywood    singer.';
	$str = preg_replace('/\s+/', ' ', $str);
	echo $str;
?>

Output:

Output
Camila Cabello is a Hollywood singer.

Example using indexed arrays

This example will contain a pattern array to replace with replacement array.

snippet
<?php		
	//declare a string
	$string = 'The slow black bear runs away from the zoo.';
	$patterns = array();
	
	//pattern to search in subject string
	$patterns[0] = '/slow/';
	$patterns[1] = '/black/';
	$patterns[2] = '/bear/';
	
	//replacement value to replace with pattern in the given search string
	$replacements = array();
	$replacements[2] = 'fox';
	$replacements[1] = 'brown';
	$replacements[0] = 'quick';
	
	//apply preg_replace function
	$newstr = preg_replace($patterns, $replacements, $string);
	echo "<b>String after replacement:</b> " .$newstr;
?>

Output:

Output
String after replacement: The fox brown quick runs away from the zoo.

In the above example, we can see that output is not same as we want. Therefore, by applying ksort() on patterns and replacements before using preg_replace(), we can get what we want to.

snippet
<?php	
	//declare a string
	$string = 'The slow black bear runs away from the zoo.';
	$patterns = array();
	
	//pattern to search in subject string
	$patterns[0] = '/slow/';
	$patterns[1] = '/black/';
	$patterns[2] = '/bear/';
	
	//replacement value to replace with pattern in the given search string
	$replacements = array();
	$replacements[2] = 'fox';
	$replacements[1] = 'brown';
	$replacements[0] = 'quick';
	
	//sort the values of both pattern and replacement
	ksort($patterns);
	ksort($replacements);
	
	//apply preg_replace function
	$newstr = preg_replace($patterns, $replacements, $string);
	echo "<b>String after replacement using ksort:</b> " .$newstr;
?>

Output:

Output
String after replacement using ksort: The quick brown fox runs away from the zoo.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +