PHP - Replacing All Occurrences using str_replace()

Introduction

str_replace() replaces all occurrences of a specified string with a new string.

The function takes three arguments:

  • the search string,
  • the replacement string, and
  • the string to search through.

It returns a copy of the original string with all instances of the search string swapped with the replacement string.

Demo

<?php
$myString = "this is a test test test,";

echo str_replace( "test", "tests", $myString );
?>/*from ww  w  .  j  a  va2  s  . c  om*/

Result

To know how many times the search string was replaced, pass in a variable as an optional fourth argument.

After the function runs, this variable holds the number of replacements:

Demo

<?php
$myString = "this is a test test test";

echo str_replace( "t", "T", $myString, $num ) . " \n ";

echo "The text was replaced $num times. \n ";
?>/* w  w  w. ja va2 s.com*/

Result

Related Topic