PHP String str_replace() function
The str_replace() function is a case-sensitive, built-in function of PHP which replaces some character of the string with other characters. It is used to replace all the occurrences of the search string with the replacement string.
The syntax of the str_replace() function is given below, which has the following four parameters.
This function follows some rules while working, which are given below:
The str_replace() function has four parameters in which three are mandatory, and the remaining one is an optional parameter. All these following parameters are described below:
$search (mandatory) - This parameter is a mandatory parameter that can have both string and array type values. The $search parameter contains the value which is going to be searched for the replacement in the $string.
$replace (mandatory) - This parameter is a mandatory parameter which is replaced with the search values. In simple words - this parameter holds that value which will replace the $search value in the $string.
$string (mandatory) - This parameter is also a mandatory parameter which is an array or string in which search and replace value is searched and replaced. It is the string or array with which we are working.
$count (mandatory) - It is the last and optional parameter. It is an integer variable which counts the number of replacements done in the string. Simply, this variable stores the total number of replacement performed on a string $string.
This function returns an array or a string with the replaced values which is based on the $string parameter.
Important Technical Details
There is the practical implementation of the str_replace() function.
Example 1: Basic example with string variable
In the above example, we can see that "Hii" is replaced with "Hello" and the number of replacement is only 1.
Note: We can pass the $search and $replace value directly in the str_replace() function.
Example 2: Replacement with array variable
To replace the multiple values in the $string, we have to take an array to store these values for replacement.
In this output, we can see that "Hii" is replaced with "Hello" and "We" is replaced with "You" and the number of replacement is 2.
Example 3: Replacement of vowels with empty string
In this example, we replace the vowels (both uppercase and lowercase) with the empty string. Here, 10 replacements are done in this string.
Example 4: Case-sensitive
The str_replace is a case-sensitive function, it is proved in the below example.
In this example, "Hello" is not replaced with "Hii" because the search string is "hello." In the second case "Hello" has replaced with "Hii" because here search string is "Hello" which matched in the string. It proves that str_replace() function is case-sensitive.
Hello world! Hii world!