VOOZH about

URL: https://www.geeksforgeeks.org/php/php-preg_replace-function/

⇱ PHP | preg_replace() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP | preg_replace() Function

Last Updated : 11 Jul, 2025

The preg_replace() function is an inbuilt function in PHP that is used to perform a regular expression for search and replace the content.

 Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Parameters: This function accepts five parameters as mentioned above and described below.

  • $pattern: This parameter contains the string element which is used to search the content and it can be a string or array of strings.
  • $replacement: It is a mandatory parameter that specifies the string or an array with strings to replace.
  • $subject: The string or an array with strings to search and replace.
  • $limit: This parameter specifies the maximum possible replacements for each pattern.
  • $count: It is an optional parameter. This variable will be filled with the number of replacements done.

Return Value: This function returns an array if the subject parameter is an array, or a string otherwise. The below programs illustrate the preg_replace() function in PHP.

Program 1: The following program replaces string by using the regular expression parameter.

Output:
November 02, 2018

Program 2 : 

Output:
preg_replace returns
Array
(
 [0] => X:Z:1
 [1] => GFG
 [2] => X:2
 [3] => GY:eY:eY:kY:s
 [4] => X:3
 [5] => GCET
 [6] => CY:oY:nY:tY:rY:iY:bY:uY:tY:e
 [7] => X:4
)

Program 3: 

Output:
Geeks***Geeks
3

Reference: https://www.php.net/manual/en/function.preg-replace.php

Comment
Article Tags: