How to Replace Characters in a String with the str_replace() Function in PHP

09/04/2021

Contents

In this article, you will learn how to replace characters in a string with the str_replace() function in PHP.

PHP str_replace() Function

The str_replace function replaces specified characters in a string with other characters.

Syntax:

str_replace($find, $replace, $string, $count)

$find: The characters to find.
$replace: The characters to replace the characters specified in $find.
$string: The string to be searched.
$count: A variable to store the number of replacements.

Sample

Replace characters in a string

Sample Code

<?php
  $str = "string001string002string003";
  echo $str;
  $str = str_replace("string", "text", $str, $n);
  echo $str;
  echo "Replacements: $n";
?>

Result

string001string002string003
text001text002text003
Replacements: 3

Replace characters in a string in an array

Sample Code

<?php
  $arr = array ("string001","string002","string003");
  print_r($arr);
  $arr = str_replace("string", "text", $arr, $n);
  print_r($arr);
  echo "<br>";
  echo "Replacements: $n";
?>

Result

Array ( [0] => string001 [1] => string002 [2] => string003 )
Array ( [0] => text001 [1] => text002 [2] => text003 )
Replacements: 3