PHP str_replace() function
The str_replace()
function in PHP is used to replace all occurrences of a substring within a string with another substring. This function is commonly used for string manipulation, such as sanitizing or modifying text.
Syntax:
- $search: The value(s) to search for (can be a string or an array of strings).
- $replace: The replacement value(s) (can be a string or an array of strings).
- $subject: The string or array of strings to perform the replacement on.
- $count (optional): If provided, this variable will be filled with the number of replacements performed.
Return Value:
- Returns a string or an array with the replaced values. If the subject is an array, the replacement is performed for each element in the array.
Example 1: Basic String Replacement
Output:
Explanation: The word "blue"
is replaced with "green"
, resulting in the new string "The sky is green."
.
Example 2: Replacing Multiple Substrings
Output:
Explanation: Both "apples"
and "oranges"
are replaced with "bananas"
and "grapes"
, respectively. You can replace multiple substrings by passing arrays to the $search and $replace parameters.
Example 3: Case-Sensitive Replacement
Output:
Explanation: The replacement did not occur because str_replace()
is case-sensitive. To perform a case-insensitive replacement, use str_ireplace()
.
Example 4: Counting the Number of Replacements
Output:
Explanation: The word "cat"
is replaced twice with "dog"
, and the $count parameter holds the number of replacements made.
Example 5: Replacing in an Array
Output:
Explanation: The word "apple"
is replaced with "kiwi"
in the first element of the array, while the other elements remain unchanged.
Example 6: Replacing with an Empty String
Output:
Explanation: The word "World"
is removed by replacing it with an empty string ""
. This technique can be used to delete specific substrings from a string.
Key Points:
str_replace()
is case-sensitive. If you want a case-insensitive replacement, usestr_ireplace()
.- You can replace multiple different substrings at once by passing arrays to the $search and $replace parameters.
- The optional $count parameter will keep track of how many replacements were made.
- This function works on both strings and arrays.
str_replace()
is very useful for modifying or cleaning up strings, such as replacing words in text, removing unwanted characters, or formatting output.