str_replace() function in PHP || PHP str_replace function
×


str_replace() function in php

0 520

PHP str_replace() function is used to replace the part of a string to another string. If the string has occurred more than one time inside the main string then all occurrence is replaced. It is an inbuilt function of PHP.

Syntax:

str_replace($find,$replace,$string,$count);

here,

  • $find represents the value to be searched into the main string. It can be either array or string. It is a required parameter.
  • $replace represents the value that is replaced with $find. It can also be either array or string. It is required.
  • $string is the main string on which all operations to be performed. It is also required.
  • $count is an optional parameter which counts the number of replacements

There are some rules which specify the working of this function.

  • If $find and $replace both are arrays then every element of $find is searched into the $string and replaced by the corresponding values in $replace.
  • If the $replace parameter is a string and $find is an array then every element of $find replaced by $replace string.

The return type of this function is either array or string depends on the type of $string.


Example 1:

<?php
$arr = array("apple","mango","banana","grapes");
$find="banana";
$replace="guava";
$new_arr=str_replace($find,$replace,$arr,$count);
echo "<pre>";
echo "Old array is : <br>";
print_r($arr);
echo "<br> New array is : <br>";
print_r($new_arr);
echo "<br> Number of replacement is :<strong>$count</strong>";
?>

Output:


Example 2:

<?php
$str="Ram and shyam are good friends.";
$find="shyam";
$replace="ramesh";
$mod_str=str_replace($find,$replace,$str);
echo "Old string is :<strong>$str</strong><br>";
echo "After replacement string is :<strong>$mod_str</strong>";
?>

Output:




Share:


Leave a Reply


Comments
    Waiting for your comments