PHP String replace: 2 examples of str_replace function

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.

PHP string replace

Experience this example online



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



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.

Was this article helpful?

Related Articles

Leave A Comment?