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 );
?>// w  ww  .j a  v a  2  s.c  o  m

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 ";
?>//from  w  ww.  j a v a2 s.  c  om

Result

Related Topic