LAST UPDATED: AUGUST 4, 2021
How to replace a word inside a string in PHP?
Answer: Using str_replace()
function.
We can use str_replace()
function to replace some characters or substring within the string. This function replaces all the occurrences of any particular word with the replacement string.
The str_replace()
method works based on the following rules given below:
- If the string which we are searching for is an array, then it returns the array.
- If the string to be searched is an array, then find and replace is performed with each element within the array.
- If both find and replace are arrays and replace has fewer elements than find, then an empty string is used as replacement.
- If the find is an array and replace is a string, then the replacement string will be used for every find value.
Syntax
str_replace(find,replace,string,count)
Example: Using str_replace()
function
In this example, we have used the str_replace()
function, with the help of which we have replaced the word there with World.
<!DOCTYPE html>
<html>
<head>
<title>string length in PHP</title>
</head>
<body>
<?PHP
$str = 'Hello there';
echo str_replace("there", "World", $str);
?>
</body>
</html>
Output
Hello World
The str_replace()
function is case-sensitive, and if we want to find and replace case insensitive string, we have to use the str_ireplace()
function.
PHP str_ireplace()
function
The str_ireplace()
function is also used to replace some characters with some other characters. This function is very much similar to the str_replace()
function. There is only one difference between both the functions and that is str_ireplace()
function performs a case-insensitive search while the str_replace()
method performs the case-sensitive search.
Example: Using str_ireplace()
function
In this example, we have used the str_ireplace()
method to replace the word st with Studytonight. Here, we have used st instead of ST because the str_ireplace() function can perform a case-insensitive search.
<!DOCTYPE html>
<html>
<head>
<title>Replace a word inside a string</title>
</head>
<body>
<?php
$str = 'Welcome to ST';
echo str_ireplace("st", "Studytonight", $str);
?>
</body>
</html>
Output
Welcome to Studytonight
Conclusion
In this lesson, we have discussed how to replace a word inside a string. To replace a word inside a string, we can use the str_replace()
function. This function performs a case-sensitive search and finds and replaces all the occurrences of a word within the string. We can use str_ireplace()
function to perform the case-insensitive search.