PHP str_replace Function: How it Works with Examples

PHP str_replace Function

If you find a word that does not fit and want to fix it. You can use the PHP str_replace function. This function helps you swap one piece of a string with another.

Understand the str_replace Function in PHP

The str_replace replaces parts of a string with new text. It searches for one value and swaps it with another.

str_replace($search, $replace, $subject, $count)
  • $search: The word or value you want to replace.
  • $replace: The new word or value.
  • $subject: The string or array you want to change.
  • $count (optional): PHP stores the number of replacements here.

Here is a quick example:

echo str_replace("world", "PHP", "Hello world");

You get “Hello PHP” because it replaces “world” with “PHP”.

The str_replace checks for exact matches. It does not replace if the case does not match.

echo str_replace("apple", "orange", "Apple pie");

This gives “Apple pie” because “apple” and “Apple” do not match.

Here are the use cases:

The Differences Between str_replace, str_ireplace and preg_replace in PHP

Each of these functions replaces text in a string. But they follow different rules.

str_replace:

  • Replaces exact text only.
  • Case matters.
  • No pattern matching.

For example:

str_replace("cat", "dog", "The cat sleeps"); 
str_replace("Cat", "dog", "The cat sleeps");

Output:

The dog sleeps
The cat sleeps

Use it when you want a case-sensitive replacement.

str_ireplace:

  • Works like str_replace.
  • Ignores case.
  • No patterns.
  • Slightly slower than str_replace

For example:

str_ireplace("Cat", "dog", "The cat sleeps");

Output:

The dog sleeps

Use it when you do not care about the letter case.

preg_replace:

  • Uses patterns (regular expressions).
  • Can match flexible formats.
  • Slower but powerful.
  • Case control with flags.

For example:

preg_replace("/cat/i", "dog", "The CAT sleeps"); 
preg_replace("/[0-9]/", "#", "Room 101");        

The output:

The dog sleeps
Room ###

Use it when you need pattern logic or dynamic matches.

Here is a table that shows you the key differences:

Featurestr_replacestr_ireplacepreg_replace
Case-sensitiveYesNoOptional (use /i)
Pattern supportNoNoYes (Regex)
SpeedFastFastSlower
Common useExact matchExact matchComplex search/replace

PHP str_replace Examples

Replace multiple values:

echo str_replace(["apple", "banana"], ["orange", "grape"], "apple and banana");

The output:

orange and grape

This swaps “apple” with “orange” and “banana” with “grape”.

str_replace(["a", "e", "i"], "*", "pineapple");

You get “p*n**ppl*”. It replaces each vowel with “*”.

Replace in arrays:

$arr =  str_replace("cat", "dog", ["cat", "wild cat", "black cat"]);
print_r($arr);

Output:

Array
(
[0] => dog
[1] => wild dog
[2] => black dog
)

This changes all “cat” values to “dog” in each array item.

$vlarray= str_replace(["red", "blue"], "color", ["red car", "blue sky"]);
print_r($vlarray);

Output:

Array
(
[0] => color car
[1] => color sky
)

It swaps each color with “color”.

Use the $count parameter:

str_replace("apple", "orange", "apple, apple, apple", $count);

Output:

orange, orange, orange

$count becomes 3 because it replaced “apple” three times.

$str = "egg, egg, egg";
str_replace("egg", "bacon", $str, $count);

The string becomes “bacon, bacon, bacon” and $count holds 3.

Replace numbers in the text:

str_replace(["1", "2"], ["one", "two"], "1, 2, 3");

You get “one, two, 3” by replacing numbers with words.

Clean up extra spaces:

str_replace("  ", " ", "This  is  a  test");

You get “This is a test” by removing extra spaces.

Wrapping Up

In this article, you learned what str_replace does and how it works with strings and arrays. You saw its syntax, how it checks for case, and how to use the $count variable. Here is a quick recap:

  • str_replace replaces text in strings or arrays.
  • It works with exact values.
  • You can replace one value or many at once.
  • Use $count to know how many changes happened.
  • Pick str_replace, str_ireplace, or preg_replace based on your case.

FAQs

What does str_replace do in PHP?

It replaces part of a string with another value. You use it to swap words, fix input, or clean up text.

Is str_replace case-sensitive?

Yes. It does not match if the case is different. Use str_ireplace to ignore case.

Can str_replace work with arrays?

Yes. You can pass arrays as input and it will handle each item.

What does the $count parameter do in str_replace?

It shows how many replacements happened. PHP stores this number in the variable you pass.

Similar Reads

History of PHP: From PHP/FI to Modern Web Development

You use PHP every day if you build websites, but most people do not know where it came from or…

PHP Singleton Pattern: How to Use with Examples

The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP Arrow Functions: Understanding “fn” Syntax

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…

Master PHP Iterables: Arrays, Objects, Traversable Interface

The first appearance of PHP iterable was in PHP version ( 7.1 ) – Iterables are a powerful feature in…

PHP array_combine: How to Merge Arrays as Key and Value

The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…

PHP array_all Function: How it Works with Examples

PHP 8.4 released a new built-in function, array_all checks to check if all array values meet a condition. It gives…

PHP File Inclusion: require, include, require_once, include_once

PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

PHP $_ENV: Manage Environment Variables

In this tutorial, we will explore a form of superglobal variable in PHP: $_ENV, which symbolizes how PHP reaches for…

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

Previous Article

PHP array_merge: Combine Multiple Arrays into One

Next Article

PHP strlen Function: How It Works with Strings

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.