← Back to Chapters

PHP String Replace Functions

? PHP String Replace Functions

? Quick Overview

PHP provides powerful string replacement functions that allow developers to search and replace substrings easily. The most commonly used functions are str_replace() and str_ireplace().

?️ Key Concepts

  • str_replace() – Case-sensitive string replacement
  • str_ireplace() – Case-insensitive string replacement
  • Multiple replacements supported

? Syntax / Theory

Both functions accept a search value, a replacement value, and the original string. They return a modified string without changing the original variable.

? Code Example: str_replace()

? View Code Example
// Replace a substring in a case-sensitive way
<?php
$string = "Hello World";
$newString = str_replace("World", "PHP", $string);
echo $newString;
?>

? Live Output / Explanation

The output will be Hello PHP because the substring World is replaced with PHP.

? Code Example: str_ireplace()

? View Code Example
// Replace a substring ignoring case sensitivity
<?php
$string = "Hello World";
$newString = str_ireplace("world", "PHP", $string);
echo $newString;
?>

? Live Output / Explanation

Even though world is lowercase, it matches World and produces Hello PHP.

? Code Example: Multiple Replacements

? View Code Example
// Replace multiple occurrences of the same word
<?php
$string = "Hello World, welcome to the World!";
$newString = str_replace("World", "PHP", $string);
echo $newString;
?>

? Use Cases

  • Cleaning user input
  • Formatting dynamic text
  • Replacing placeholders in templates
  • Search-and-replace operations in CMS systems

? Interactive Visual Explanation

World PHP

✅ Tips & Best Practices

  • Use str_replace() for exact case matches
  • Use str_ireplace() when case does not matter
  • Both functions replace all occurrences automatically
  • For pattern-based replacement, use regular expressions

? Try It Yourself

  • Replace "apple" with "orange" in a string
  • Perform a case-insensitive replacement
  • Replace multiple words using arrays in str_replace()