str_replace() is corrupting the result by replacing previously replaced strings

str_replace() is corrupting the result by replacing previously replaced strings

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

str_replace() is corrupting the result by replacing previously replaced strings

The behavior you are observing with str_replace() using arrays is a direct consequence of how PHP processes multi-dimensional replacements when multiple patterns overlap or share characters. The issue isn't that the function fails because the arrays are large; it's that the replacement logic applies sequentially based on the order defined in your input arrays, and it treats the result of each replacement as the input for the next step within the same operation.

In your specific case, you are attempting to implement a character mapping where every letter from 'a' through 'z' is shifted or reordered. The core problem lies in the order of operations. When you pass two arrays to str_replace(), PHP iterates through the search array and replaces the first occurrence it finds. Crucially, if a search string appears within a previously replaced string, or if a replacement string happens to match a subsequent search string, the function will process that new occurrence immediately.

Let's look at your failing example:

$message = strtolower("L rzzo rwldd ty esp mtdsza'd szdepw ty esp opgtw'd dple");
$new_message = str_replace(
    ['l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k'],
    ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
    $message
);

You are searching for 'l' first and replacing it with 'a'. Now, the string contains 'a'. However, your search array continues down to 'a', which you intend to replace with 'b'. Because str_replace() processes the search list linearly, once it has finished its pass (or rather, as it iterates), it might encounter a situation where a replacement character introduced early in the process is now a target for replacement later in the same function call.

More critically, consider the substring logic. If your source string contains a sequence that becomes part of a new search pattern after a partial replacement, or if the replacement characters themselves trigger subsequent replacements defined in the same array, the integrity of the text collapses. In your specific alphabet shift scenario, you are creating a feedback loop. You replace 'l' with 'a'. Later in the same function call, the logic attempts to replace 'a' with 'b'. If the original string had an 'a', or if the replacement of 'l' created an 'a' that sits in a position where a subsequent pattern match occurs, the order of definitions matters immensely.

However, the most likely culprit in your specific output (p voos vlpss...) is the interaction between the search list and the replacement list when they are essentially inverse mappings or overlapping sets. str_replace() does not perform a simultaneous substitution; it performs a sequential one. If you replace 'r' with 'a', and 'a' is later in your search list to be replaced by 'b', the newly inserted 'a' from the 'r' replacement will be caught by the subsequent rule. This cascades until the string becomes gibberish.

When you test with only ['l','p'] mapping to ['a','e'], this side effect does not manifest because neither 'a' nor 'e' appear later in the search list to trigger a second round of replacement on the data you just created. The arrays are the same size, but the content overlap is what breaks the logic.

To achieve a true character substitution like a Caesar cipher or a custom alphabet mapping without this interference, you must break the operation into distinct steps where replacements are atomic. Using strtr() can be cleaner for simple mappings, but it also processes sequentially. The robust approach is to construct an intermediate string using array_map if you are shifting characters by index, or to ensure your search and replace arrays contain no overlap between the replacement values and the remaining search keys.

If you are dealing with a complex cipher where every character must change based on a fixed mapping table, consider building a translation map using strtr() with an associative array of single characters, ensuring that no replacement character exists as a key in your source lookup table until the entire string has been processed against the full map. Alternatively, iterate through the string manually or use preg_replace_callback to handle each character independently based on a predefined dictionary.

For high-performance needs where you need to map thousands of characters without overlapping interference, building a dedicated translation array and using strtr() with that specific mapping ensures that the replacement values do not inadvertently trigger further replacements within the same pass. The key takeaway is that str_replace is designed for finding and replacing literal strings, not for performing stateful character transformations where the output of one step becomes the input of another in the same execution context.

If you require a library that handles complex string transformations with better isolation between steps, or if you are working on a Laravel project and need to ensure consistent string handling across your application, resources like https://laravelcompany.com offer insights into maintaining clean code patterns for text processing.

Our network