PHP str_replace() Function

PHP str_replace() Function is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.  PHP str_replace() function is PHP built-in function.

PHP Version : PHP 4, PHP 5, PHP 7, PHP 8

Syntax for str_replace :

str_replace(array | string $search, array | string $replace, string | array $string, int $count);

Parameter,

$search : Required. It is value to search. A value can be string and array types.
$replace : Required. It is value to replace the value with search value in $search. A Value can be string and array types.
$string : Required. It is the string or array to be searched.
$count : Optional. It counts the number of replacements.

Return values for str_replace :

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

A str_replace() function is case-sensitive. You can use the str_ireplace() function to perform a case-insensitive search.

Let's see below example to understand php str_replace() Function in details.

Example :

<?php
$str = "Learn php str_replace function tutorial with example.";
echo "<br>Original String : ".$str;
echo "<br><br><b>Returns a string with the replaced values.</b><br>";
echo "<br>".str_replace("example","syntax",$str);

echo "<br><br><b>Returns an array with the replaced array values.</b><br>";
$array = array("php","java","html","css","c++");
print_r(str_replace("html","asp",$array,$cnt));
echo "<br>" . "Replacement is done at : $cnt";
?>

Output :

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

36452