str_replace() function in PHP


The str_replace() function is used to replace a string with another string.

Note  − The function is case-sensitive.

Syntax

str_replace(find, replace, str, count)

Parameters

  • find − The value to search

  • replace − The string with which we want to replace the $find

  • str − The string to be searched

  • count − The number of replacements

Return

The str_replace() function returns a string or an array with the replaced values.

Example

The following is an example −

 Live Demo

<?php
$str = "I am Amit";
$res = str_replace("Amit", "David", $str);
echo $res;
?>

Output

I am David

Example

The following is an example −

 Live Demo

<?php
$myArr = array("one","two","three");
print_r(str_replace("three","four",$myArr,$c));
echo "<br>" . "Number of Replacements = $c";
?>

Output

Array (
   [0] => one
   [1] => two
   [2] => four
)
<br> Number of Replacements = 1

Updated on: 24-Jun-2020

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements