preg_replace() function in PHP || PHP Functions
×


preg_replace() function in php

2540

PHP preg_replace() function is used to search a particular content in a string and replace it with another content with the help of a regular expression. It is an inbuilt function of PHP.

The return type of this function depends on the input parameter given for replacement. If the input is an array then this function returns an array and in case of string it returns a string.

Syntax:

preg_replace($regular_expression,$replacement_content,$sub,$limit,$count);

here,

  • $regular_expression represents the code that we used to search the content. It can be either an array or a string. It is required.
  • $replacement_content represents the code that replaces to string. it can also be either an array or a string. It is also a mandatory parameter.
  • $sub: this is the code with the strings to search and replace. It can also be either an array or a string.
  • $limit: it is a numeric value that represents the maximum number of possible replacements for each regular expression or pattern.
  • $count: it is also a numeric value that represents the number of replacements done by the function. It is an optional parameter.

Example:

<?php
$pattern = '/aa/';
$replacement_content='a';
$sub='aabaabaadaafaagaahaaiaajaak';
$result = preg_replace($pattern,$replacement_content,$sub); // it will replace all double a with single a
echo "Old string is : $sub <br>";
echo "After replacement new string is : $result";
?>

Output:



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments