PHP str_replace() Function

PHP

PHP str_replace() - Replace Substrings

Learn PHP str_replace() function. Replace all occurrences of a search string with a replacement efficiently and easily. This tutorial covers everything you need to know about str_replace() including setup, usage, examples, best practices, common pitfalls, and interview questions.

Introduction

PHP's str_replace() function is a powerful built-in string function used to replace all occurrences of a specified substring with a replacement string. It is often used in scenarios where you want to modify text dynamically by searching and replacing specific words or phrases within strings.

This function belongs to the String category in PHP and is essential for string manipulation.

Prerequisites

  • Basic knowledge of PHP including variables and strings.
  • PHP installed on your system (version PHP 5+ recommended, as str_replace() is available since PHP 4).
  • Basic understanding of how to run PHP scripts (e.g., via CLI or web server).

Setup Steps

  1. Install PHP: Download and install PHP from the official site php.net if not already installed.
  2. Create a PHP file: Create a new file called replace_example.php.
  3. Open the file in your editor: Use any code editor like VSCode, Sublime Text, or PHPStorm.
  4. Write your PHP script: Implement str_replace() examples as below.
  5. Run the script: Execute from the command line using php replace_example.php or within a browser by placing the file in your web server root.

Understanding PHP str_replace() Function

str_replace() has this basic syntax:

str_replace(mixed $search, mixed $replace, mixed $subject[, int &$count]): mixed
  • $search: The value to look for. Can be a string or an array of strings.
  • $replace: The replacement value. Can be a string or an array.
  • $subject: The string or array of strings to be searched and replaced.
  • $count (optional): If passed, will hold the number of replacements performed.
  • Returns the modified string or array with replacements.

Examples

Example 1: Basic Replacement in a String

<?php
$text = "Hello world!";
$search = "world";
$replace = "PHP";
$result = str_replace($search, $replace, $text);
echo $result;  // Outputs: Hello PHP!
?>

Example 2: Replacing Multiple Occurrences

<?php
$text = "red, green, red, blue, red";
$replaced = str_replace("red", "yellow", $text);
echo $replaced;  // Outputs: yellow, green, yellow, blue, yellow
?>

Example 3: Case Sensitive Replacement (Note)

str_replace() is case-sensitive. See the difference below:

<?php
$text = "Hello World!";
echo str_replace("world", "PHP", $text); // Outputs: Hello World! (no change)
echo str_replace("World", "PHP", $text); // Outputs: Hello PHP!
?>

Example 4: Using Arrays for Search and Replace

<?php
$text = "I like fruits: apple, banana and orange.";
$search = ["apple", "banana", "orange"];
$replace = ["pear", "kiwi", "grape"];
$result = str_replace($search, $replace, $text);
echo $result;  // Outputs: I like fruits: pear, kiwi and grape.
?>

Example 5: Counting Replacements

<?php
$text = "foo bar foo baz foo";
$count = 0;
$newText = str_replace("foo", "bar", $text, $count);
echo $newText;    // Outputs: bar bar bar baz bar
echo "<br>Replacements done: " . $count;  // Outputs: Replacements done: 3
?>

Best Practices

  • Case Sensitivity: Remember str_replace() is case-sensitive. Use str_ireplace() if a case-insensitive replacement is needed.
  • Handling Arrays: When using arrays for $search and $replace, ensure they are of equal length or carefully planned to avoid unexpected replacements.
  • Sanitize Inputs: If replacement strings or subjects come from user input, validate or sanitize them to avoid unwanted output or security issues.
  • Performance Consideration: For large texts or many replacements, test the performance, especially when using arrays.
  • Use $count: Utilize the optional $count parameter for debugging or analytics on how many replacements occurred.

Common Mistakes

  • Confusing str_replace() with preg_replace(); the former does literal search, latter uses regex.
  • Expecting case-insensitive matching when using str_replace() (it’s case-sensitive).
  • Misaligning $search and $replace arrays leading to wrong replacements.
  • Forgetting that str_replace() returns a new string and does not modify the original variable unless reassigned.
  • Passing null or non-string types to the function, which can cause unexpected output.

Interview Questions

Junior Level

  • Q1: What does str_replace() do in PHP?
    A: It replaces all occurrences of a given search string with a replacement string in a target string.
  • Q2: Is str_replace() case-sensitive?
    A: Yes, it is case-sensitive.
  • Q3: Can str_replace() replace multiple words at once?
    A: Yes, by passing arrays as the $search and $replace parameters.
  • Q4: Does str_replace() modify the original string variable?
    A: No, it returns a new string with replacements; you must assign it back if you want to keep changes.
  • Q5: What is the optional fourth parameter in str_replace() used for?
    A: To count the number of replacements made.

Mid Level

  • Q1: How does str_replace() behave when $search and $replace arrays differ in length?
    A: PHP pairs each element from $search with the corresponding index in $replace; if $replace has fewer elements, missing replacements default to empty strings.
  • Q2: What is the difference between str_replace() and str_ireplace()?
    A: str_replace() is case-sensitive, while str_ireplace() performs case-insensitive replacements.
  • Q3: Can str_replace() be used on arrays?
    A: Yes, it accepts arrays as the subject and will perform replacements on each element.
  • Q4: How does the order of replacement affect complex str_replace() calls with arrays?
    A: Replacements happen sequentially; unexpected results can occur if one replacement creates a new search string for subsequent replacements.
  • Q5: How can you count how many replacements were made by str_replace()?
    A: Use the optional fourth parameter to receive the count by reference.

Senior Level

  • Q1: How would you safely perform multiple replacements to avoid overlapping or recursive substitutions with str_replace()?
    A: By ordering replacements properly, or using placeholders to separate substitutions, or using regex functions if necessary.
  • Q2: Explain the internal behavior of str_replace() when replacing strings in terms of memory and copying.
    A: It creates a new string copy internally as strings are immutable in PHP. Replacements involve scanning and rebuilding the string, which could be memory expensive for large strings.
  • Q3: How can you handle partial replacements with str_replace() when only the first occurrence should be replaced?
    A: str_replace() replaces all occurrences; for first occurrence only, use preg_replace() with a limit or write custom logic.
  • Q4: Describe any limitations of str_replace() concerning multibyte character sets.
    A: str_replace() works on bytes and may misbehave with multibyte encodings, potentially breaking characters. Consider using multibyte-safe alternatives or functions for such cases.
  • Q5: How would you optimize a PHP script heavily using str_replace() on large texts?
    A: Minimize repeated calls, combine replacements with arrays when possible, use output buffering, or switch to regex replacements if patterns require it.

FAQ

  • Q: Can str_replace() replace substrings in an array of strings?
    A: Yes, pass the array as the $subject, and str_replace() will return an array with replacements applied to each element.
  • Q: What if the $search string is not found?
    A: The original string is returned unchanged.
  • Q: Is str_replace() Unicode-aware?
    A: It operates byte-wise and can have issues with multibyte strings; use multibyte-safe functions or careful testing if working with Unicode.
  • Q: Can str_replace() be used to remove substrings?
    A: Yes, by setting the $replace parameter to an empty string.
  • Q: What should I do if I want case-insensitive replacement?
    A: Use str_ireplace(), which works exactly like str_replace() but ignores case.

Conclusion

The PHP str_replace() function is essential for any developer dealing with string manipulation. It offers a simple yet powerful way to search and replace substrings β€” either individually or in bulk using arrays. By understanding its syntax, parameters, and nuances like case sensitivity and array handling, you can effectively implement find-and-replace operations with confidence.

Apply the best practices shared here and watch out for common mistakes to ensure your PHP string replacements are bug-free and performant.

Whether for quick text substitutions or complex transformations, str_replace() is a reliable tool in the string manipulation toolbox.