strtr ($str, array ('a' => '<replacement>'));

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
Answer from zrvan on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.str-replace.php
PHP: str_replace - Manual
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array. For example: <?php $replace = array( 'dog' => 'cat', 'apple' => 'orange' 'chevy' => 'ford' ); $string = 'I like to eat an apple with my dog in my chevy'; echo str_replace_assoc($replace,$string); // Echo: I like to eat an orange with my cat in my ford ?> Here is the function: <?php function strReplaceAssoc(array $replace, $subject) { return str_replace(array_keys($replace), array_values($replace), $subject); } ?> [Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_string_str_replace.asp
PHP str_replace() Function
If find is an array and replace is a string, the replace string will be used for every find value ยท Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.
Discussions

php - How do I replace certain parts of my string? - Stack Overflow
How can I replace a certain part of my string with another one? Input string: "Hello, my name is Santa" How can I change all a's in my string with something else? I think I need a foreach loop, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I replace part of a string in PHP? - Stack Overflow
I am trying to get the first 10 characters of a string and want to replace space with '_'. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Realized emojis could be used in php code so I decided to give a try.
What fresh hell is this More on reddit.com
๐ŸŒ r/PHP
58
145
September 19, 2014
"Support variable names without dollar sign"
I challenge anyone to defend the need for the dollar sign. More on reddit.com
๐ŸŒ r/PHP
154
93
March 31, 2011
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ zcmyga8t โ€บ php-string-replace-example
How do I replace a string in PHP?
January 14, 2023 - The main difference between preg_replace() and str_replace() functions is that preg_replace() will perform Regular Expression pattern matching, while str_replace() will replace a specific string with another string, and it will be much faster ...
Top answer
1 of 4
27
strtr ($str, array ('a' => '<replacement>'));

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
2 of 4
27

Search & Replace

There are a few different functions/methods to replace a certain part of a string with something else, all with their own advantages.


##str_replace() method (binary safe; case-sensitive)

Arguments

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

str_replace() has 3 required arguments as you can see in the above definition with the correct order, all of which can take a string as also an array as argument!

Search & Replace

  • search(string) AND replace(string) โ†’ Replaces the search string with the replace string.

  • search(array) AND replace(string) โ†’ Replaces all search elements with the replace string.

  • search(string) AND replace(array) โ†’ Throws you a notice: "Notice: Array to string conversion", because a replacement array for just one search string doesn't make sense, so it tries to convert the array to a string.

  • search(array) AND replace(array) โ†’ Replaces each search element with the corresponding replace element (Keys are ignored!).

  • search(more elements) AND replace(less elements) โ†’ Replaces each search element with the corresponding replace element (For the missing replace elements an empty string will be used).

  • search(less elements) AND replace(more elements) โ†’ Replaces each search element with the corresponding replace element (Unneeded replace elements are ignored).

Subject

  • subject(string) โ†’ Replacement is done for the subject string.

  • subject(array) โ†’ Replacement is done for each array element.

Code

echo str_replace("search", "replace", "text search text");
echo str_replace(["t", "a"], "X", "text search text");
echo str_replace("search", ["replace1", "replace2"], "text search text");
echo str_replace(["a", "c"], ["X", "Y"], "text search text");

Output

text replace text
XexX seXrch XexX
Notice: Array to string conversion
text seXrYh text

Notes

  1. Gotcha!

Important to know is that str_replace() works from left to right of the array. This means it can possible replace a value which you already replaced. For example:

    echo str_replace(array("a", "b"), array("b", "c"), "aabb");
    //Probably expected output: bbcc
    //Actual output:            cccc
  1. Case insensitive

If you want to make the search case insensitive you can use str_ireplace() (Notice the i for case-insensitive).

  1. Multidimensional array

str_replace()/str_ireplace() does NOT work for multidimensional arrays. See this manual comment for such an implementation. Of course you can also replace str_replace() with str_ireplace() for case-insensitive.

If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:

<?php 
function str_ireplace_deep($search, $replace, $subject) 
{ 
if (is_array($subject)) 
{ 
    foreach($subject as &$oneSubject) 
        $oneSubject = str_ireplace_deep($search, $replace, $oneSubject); 
    unset($oneSubject); 
    return $subject; 
} else { 
    return str_ireplace($search, $replace, $subject); 
} 
} 
?>


##strtr() method (50% binary safe; case-sensitive)

Arguments

string strtr ( string $str , string $from , string $to )

string strtr ( string $str , array $replace_pairs )

The function either takes 3 arguments with a from and to string or it takes 2 arguments with a replacement array array("search" => "replace" /* , ... */), all of which you can see in the above definition with the correct order.

2 Arguments

It starts to replace the longest key with the corresponding value and does this until it replaced all key => value pairs. In this case the function is binary safe, since it uses the entire key/value.

3 Arguments

It replaces the from argument with the to argument in the subject byte by byte. So it is not binary safe!

If the from and to arguments are of unequal length the replacement will stop when it reaches the end of the shorter string.

Subject

It doesn't accept an array as subject, just a string.

Code

echo strtr("text search text", "ax", "XY");;
echo strtr("text search text", ["search" => "replace"]);

Output

teYt seXrch teYt
text replace text

Notes

  1. Gotcha!

Opposed to str_replace(), strtr() does NOT replace replaced strings. As an example:

    echo strtr("aabb", ["a" => "b", "b" => "c"]);
    //If expecting to replace replacements: cccc
    //Actual output:                        bbcc

Also if you want to replace multiple things with the same string you can use array_fill_keys() to fill up your replacement array with the value.

  1. Case insensitive

strtr() is NOT case-insensitive NOR is there a case-insensitive equivalent function. See this manual comment for a case-insensitive implementation.

  1. Multidimensional array

strtr() does opposed to str_replace() NOT work with arrays as subject, so it also does NOT work with multidimensional arrays. You can of course use the code above from str_replace() for multidimensional arrays and just use it with strtr() or the implementation of stritr().

If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:

<?php
if(!function_exists("stritr")){
function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
    if(  is_string( $one )  ){
        $two = strval( one = substr(  $one, 0, min( strlen($one), strlen(two = substr(  $two, 0, min( strlen($one), strlen(product = strtr(  $string, ( strtoupper($one) . strtolower(two . $two )  );
        return $product;
    }
    else if(  is_array( $one )  ){
        $pos1 = 0;
        $product = $string;
        while(  count( $one ) > 0  ){
            $positions = array();
            foreach(  from => $to  ){
                if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                    unset(  from ]  );
                }
                else{
                    $positions[ $from ] = $pos2;
                }
            }
            if(  count( $one ) <= 0  )break;
            $winner = min( $positions );
            $key = array_search(  $winner, $positions  );
            $product = (   substr(  $product, 0, $winner  ) . key] . substr(  $product, ( $winner + strlen(pos1 = (  $winner + strlen( key] )  );
        }
        return $product;
    }
    else{
        return $string;
    }
}/* endfunction stritr */
}/* endfunction exists stritr */

function stritr_deep($string, $one = NULL, $two = NULL){
if (is_array($string)) 
{ 
    foreach($string as &$oneSubject) 
        $oneSubject = stritr($string, two); 
    unset($oneSubject); 
    return $string; 
} else { 
    return stritr($string, two); 
} 

}
?>


##preg_replace() method (binary safe; case-sensitive)

Arguments

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

preg_replace() has 3 required parameters in the order shown above. Now all 3 of them can take a string as also an array as argument!

Search & Replace

  • search(string) AND replace(string) โ†’ Replaces all matches of the search regex with the replace string.

  • search(array) AND replace(string) โ†’ Replaces all matches of each search regex with the replace string.

  • search(string) AND replace(array) โ†’ Throws you a warning: "Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array", because a replacement array for just one search regex doesn't make sense.

  • search(array) AND replace(array) โ†’ Replaces all matches of each search regex with the corresponding replace element(Keys are ignored!).

  • search(more elements) AND replace(less elements) โ†’ Replaces all matches of each search regex with the corresponding replace element(For the missing replace elements an empty string will be used).

  • search(less elements) AND replace(more elements) โ†’ Replaces all matches of each search regex with the corresponding replace element(Unneeded replace elements are ignored).

Subject

  • subject(string) โ†’ Replacement is done for the subject string.

  • subject(array) โ†’ Replacement is done for each array element.

Please note again: The search must be a regular expression! This means it needs delimiters and special characters need to be escaped.

Code

echo preg_replace("/search/", "replace", "text search text");
echo preg_replace(["/t/", "/a/"], "X", "text search text");
echo preg_replace("/search/", ["replace1", "replace2"], "text search text");
echo preg_replace(["a", "c"], ["X", "Y"], "text search text");

Output

text replace text
XexX seXrch XexX
Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
text seXrYh text

Notes

  1. Gotcha!

Same as str_replace(), preg_replace() works from left to right of the array. This means it can possible replace a value which you already replaced. For example:

    echo preg_replace(["/a/", "/b/"], ["b", "c"], "aabb");
    //Probably expected output: bbcc
    //Actual output:            cccc
  1. Case insensitive

Since the search argument is a regular expression you can simply pass the flag i for case-insensitive search.

  1. Multidimensional array

preg_replace() does NOT work for multidimensional arrays.

  1. Backreference

Be aware that you can use \\n/$n as backreference to your capturing groups of the regex. Where 0 is the entire match and 1-99 for your capturing groups.

Also if the backreference is immediately followed by a number you have to use \${n}.

  1. Replacement / "The /e modifier is deprecated"

The replacement in preg_replace() can't use callback functions as replacements. So you have to use preg_replace_callback(). Same when you use the modifier e and get "Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead". See: Replace preg_replace() e modifier with preg_replace_callback

If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:

<?php
function preg_replace_deep($search, $replace, $subject) 
{ 
if (is_array($subject)) 
{ 
    foreach($subject as &$oneSubject) 
        $oneSubject = preg_replace_deep($search, $replace, $oneSubject); 
    unset($oneSubject); 
    return $subject; 
} else { 
    return preg_replace($search, $replace, $subject); 
} 
} 
?>


##Loops while / for / foreach method (NOT binary safe; case-sensitive)

Now of course besides all of those functions you can also use a simple loop to loop through the string and replace each search => replace pair which you have.

But this gets way more complex when you do it binary safe, case-insensitive and for multidimensional arrays than just using the functions above. So I won't include any examples here.



Affected String

Right now all methods shown above do the replacement over the entire string. But sometimes you want to replace something only for a certain part of your string.

For this you probably want to/can use substr_replace(). Or another common method is to use substr() and apply the replacement only on that particular substring and put the string together afterwards. Of course you could also modify your regex or do something else to not apply the replacement to the entire string.

๐ŸŒ
W3Schools
www-db.deis.unibo.it โ€บ courses โ€บ TW โ€บ DOCS โ€บ w3schools โ€บ php โ€บ func_string_str_replace.asp.html
PHP str_replace() Function
If find is an array and replace is a string, the replace string will be used for every find value ยท Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search. Note: This function is binary-safe. ... <?php $arr = array("blue","red","green",...
๐ŸŒ
Benjamin Crozat
benjamincrozat.com โ€บ home โ€บ blog โ€บ php str_replace(): examples, gotchas, and alternatives
PHP str_replace(): examples, gotchas, and alternatives
1 month ago - str_replace( string|array $search, string|array $replace, string|array $subject, int &$count = null ) : string|array
๐ŸŒ
PHP Tutorial
phptutorial.net โ€บ home โ€บ php tutorial โ€บ php str_replace
PHP str_replace - PHP Tutorial
April 7, 2025 - The PHP str_replace() function returns a new string with all occurrences of a substring replaced with another string.
Find elsewhere
๐ŸŒ
Arievisser
arievisser.com โ€บ blog โ€บ replace-multiple-items-from-string-text-in-php-with-array
Replace Multiple Items From String Text in PHP With Array | Arie Visser
You can combine this with the array_keys function to replace multiple items from a string with an associative array. ... $subject = 'PHP is dead since 10 years ago'; $replace = [ 'is dead' => 'will be alive', 'since 10 years ago' => 'forever', ]; str_replace(array_keys($replace), $replace, $subject);...
๐ŸŒ
Phpmentoring
phpmentoring.org โ€บ blog โ€บ php-str-replace
PHP Str_Replace() Function - How To Replace Characters In A String In PHP
The PHP str_replace() function is a built-in text processing function that is used to replace all the occurrences of a given search string or array with a replacement string or array in a given string or array.
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ php โ€บ string functions โ€บ str_replace()
PHP | String Functions | str_replace() | Codecademy
July 28, 2023 - The str_replace() function returns a string with occurrences of a specified substring replaced by another string.
๐ŸŒ
Envato Tuts+
code.tutsplus.com โ€บ home โ€บ php
How to Replace Strings in PHP | Envato Tuts+ - Code
March 25, 2021 - In this tutorial, we have covered different situations that might arise when we are replacing strings in PHP. The str_replace() function is ideal for any such basic replacements. However, it is important to be careful with the values that we ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-replace-part-of-a-string-with-another-string-in-php
How to Replace Part of a string with Another String in PHP? - GeeksforGeeks
July 23, 2025 - Example: In this example, the strtr() function takes two arguments: the input string and an associative array where the keys are the substrings to be replaced and the values are the corresponding replacements.
๐ŸŒ
Udemy
blog.udemy.com โ€บ home โ€บ it & development โ€บ web development โ€บ how to use the php str_replace function to find and replace strings
How to Use the PHP STR_REPLACE Function - Udemy Blog
April 14, 2026 - The PHP `str_replace()` function searches a string or array and replaces every matching instance with a new value. This article covers its syntax, parameters, case sensitivity, empty-string replacements, and array usage.
๐ŸŒ
Matt Doyle
elated.com โ€บ home โ€บ blog โ€บ replacing text in php strings
Replacing Text in PHP Strings
July 23, 2022 - Explains how to replace chunks of text inside PHP strings using str_replace() and substr_replace(). Also looks at deleting and inserting text.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-replace-a-text-in-a-string-with-another-text-using-php
How to replace a text in a string with another text using PHP ? - GeeksforGeeks
July 23, 2025 - In case, we wish to replace the string irrespective of the case in which the old string is in, the str_ireplace() method is used. The method is supported in PHP 5+. The string behaves in a similar manner as compared to the str_replace() method.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ php_function_str_replace.htm
PHP String str_replace() Function
The PHP String str_replace() function is used to replace all occurrences of the search string or array of search strings with a replacement string or array of replacement strings in the given string or array, respectively.