• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / PHP / php str_replace – Replace String in php

php str_replace – Replace String in php

December 13, 2021 Leave a Comment

You can use the php str_replace() function to replace strings in a string or an array of strings with a replacement string in the following way:

$old_string = "This is the old string";
$new_string = str_replace("old","new",$old_string);

echo $new_string;  // "This is the new string" 

From the php documentation, the php str_replace() function takes 4 parameters:

str_replace(
    array|string $search,
    array|string $replace,
    string|array $subject,
    int &$count = null
)

The first parameter is the string (or array of strings) we want to search for. The second parameter is what we will replace the first parameter with. The third parameter is the string (or array of strings) we will be searching.

You can also pass a fourth parameter which will return the number of times a replacement occurred.

If you want to do case-insensitive string replacement, you can use the php str_ireplace() function.

Using str_replace() Function to Replace a String with php

We can use the php str_replace() function to replace a letters or words in a string very easily in our php code.

Let’s say I have the following string:

$hello_text = "Hello!";

If I want to replace the word “Hello” with “Good Bye”, we can easily do that with the following call to str_replace():

$hello_text = "Hello!";
echo str_replace("Hello","Good Bye",$hello_text);  // Good Bye!

You can use the str_replace() function to replace any string with any other string.

If we wanted to replace all of the “e”s with “a”s in our string, we would just pass “a” as the second parameter.

$hello_text = "Hello!";
echo str_replace("e","a",$hello_text);  // Hallo!

Replacing Multiple Strings with str_replace()

One of the cool things with the php str_replace() function is you can replace multiple strings in a string by passing in arrays of different values to the function.

Let’s say I have the following string:

$hello_text = "3 Things I Like are Flowers, Rabbits and Lions.";

We can replace the 3 things we like with 3 other things by passing an array to str_replace():

$hello_text = "3 Things I Like are Flowers, Rabbits and Lions.";

echo str_replace(array("Flowers","Rabbits","Lions"),array("Lemonade","Fish","Driving"), $hello_text); // "3 Things I Like are Lemonade, Fish and Driving."

There are a few things to note here.

First, if the first parameter is an array and the second parameter is a string, the replacement string will be used for all replacements.

$hello_text = "3 Things I Like are Flowers, Rabbits and Lions.";

echo str_replace(array("Flowers","Rabbits","Lions"),"Lemonade", $hello_text); // "3 Things I Like are Lemonade, Lemonade and Lemonade."

Second, if the first parameter is an array and the second parameter is an array with length shorter than the first parameter, an empty string will be used for the remaining replacements.

$hello_text = "3 Things I Like are Flowers, Rabbits and Lions.";

echo str_replace(array("Flowers","Rabbits","Lions"),array("Lemonade","Fish"), $hello_text); // "3 Things I Like are Lemonade, Fish and  ."

Replacing Strings in an Array with str_replace()

We can also replace strings in an array of strings with the php str_replace() function.

Let’s say I have the following array of strings:

$array_of_strings = array("This","is","an","array","of","strings");

If we want to replace all of the “a”s with “e”s, str_replace() will make the appropriate replacements on each element of the array.

$array_of_strings = array("This","is","an","array","of","strings");

echo json_encode(str_replace("a","e", $array_of_strings)); // ["This","is","en","errey","of","strings");

How to Fix str_replace() if it is Not Working

With str_replace(), the algorithm works from left to right and we need to be careful with repeated patterns and the order in which we are doing replacements.

This is most important when we are making multiple replacements.

For example, let’s say we have the following string and we want to replace the e with elephant and l with lion.

$sample_string = "e l";
$search_arr = array("e","l");
$replace_arr = array("elephant","lion");

echo str_replace($search_arr,$replace_arr, $sample_string); // What is the output??

We might expect the output to be “elephant lion”, but str_replace() doesn’t quite work like this.

The actual output from the code above is:

$sample_string = "e l";
$search_arr = array("e","l");
$replace_arr = array("elephant","lion");

echo str_replace($search_arr,$replace_arr, $sample_string); // elionephant lion

This is because the code first sees “e” at the beginning and makes a replacement. So now we have “elephant l”. However, the code is still on the first letter and now will go to the second letter. The second letter is “l”. So the code makes another replacement, replacing “lion” for “l”.

So now we have “elionephant l”. There are no more “e”s or “l”s until the final letter, where str_replace() makes the final replacement.

In this case, you may want to use the php strtr() function to replace substrings.

Examples of Replacing Characters with Other Characters using str_replace() in php

Below are a few more examples of how you can use the str_replace() function to make replacements in strings in php.

For example, if we want to replace spaces with dashes, we can do the following.

$string_with_spaces = "This is a string.";

$string_with_dashes = str_replace(" ","-", $string_with_spaces);

echo $string_with_dashes;

// Output:
This-is-a-string.

Another example is if we want to replace underscores with spaces, we can do the following.

$string_with_underscores = "This_is_a_string.";

$string_with_spaces = str_replace("_"," ", $string_with_underscores);

echo $string_with_spaces ;

// Output:
This is a string.

Hopefully this article has been helpful for you to understand how you can use the php str_replace() function to replace strings with other strings in your php code.

Other Articles You'll Also Like:

  • 1.  php property_exists() – Check if Property Exists in Class or Object
  • 2.  Get Days in Month Using php
  • 3.  Get First Element of Array in php
  • 4.  Using php to Copy Files Easily from One Directory to Another
  • 5.  php print_r() Function- Get Information about Variables in php
  • 6.  PHP Numerically Indexed Array Begin With Position 0
  • 7.  Capitalize First Letter of String with php ucfirst() Function
  • 8.  php is_array() Function – Check if Variable is Array in php
  • 9.  php atan – Find Arctangent and Inverse Tangent of Number
  • 10.  php json_encode() Function – Get JSON Representation of Variables in php

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy