Quick Reach
The String replace function in PHP
In order to replace words in PHP strings with other words, you can use the string replace function str_replace() in PHP.
See an example of string replace
In this chapter, you will learn the syntax of PHP string replace function as well as examples to replace strings.
Syntax of string replace function
The complete syntax of string replace function in PHP is:
str_replace(find,replace,string,count)
Where str_replace requires three parameters:
- Find (value to be replaced)
- Replace (value to be replaced by)
- String (Static or string variable or array)
- Count is optional
PHP replace string example by using str_replace()
In the following example, the name in the given string “Hello Mike” will be replaced by “Peter” by using the str_replace function. The end result is displayed by using the echo statement.
Experience this example online
1
2
3
4
5
|
<?php
echo str_replace("Mike","Peter","Hello Mike!");
?>
|
Output
Hello Peter!
String replace with variables
In the following example, a string variable is used in the str_replace method.
Experience this example online
1
2
3
4
5
6
7
|
<?php
$strReplaceExample = "Hello Mike";
echo str_replace("Mike","Peter",$strReplaceExample);
?>
|
Output
Hello Peter!
Note, the PHP str_replace is case sensitive. If you need to replace string in PHP for case insensitive strings then use the str_ireplace() Function.
Leave A Comment?