strtr

strtr(string $string, string $from, string $to): string — strtr(string $string, array $replace_pairs): string

String translation: the two-string form maps characters one-to-one, the array form matches longest key first in a single pass without rescanning replaced text — the classic contrast with str_replace's order-sensitive cascading.

C C23

C23
#include <stdio.h>
#include <string.h>

// literal replace-all helper (what str_replace does: one pair at a time)
static void replace_all(char *dst, const char *s, const char *from, const char *to) {
    int w = 0;
    size_t flen = strlen(from);
    for (int i = 0; s[i];) {
        if (strncmp(s + i, from, flen) == 0) {
            strcpy(dst + w, to);
            w += strlen(to);
            i += flen;
        } else {
            dst[w++] = s[i++];
        }
    }
    dst[w] = '\0';
}

// strtr array form: longest key first (caller passes keys sorted), single pass,
// replaced text is never re-scanned
static void strtr(const char *s, const char *from[], const char *to[], int n, char *out) {
    int w = 0;
    for (int i = 0; s[i];) {
        int matched = 0;
        for (int k = 0; k < n; k++) {
            size_t len = strlen(from[k]);
            if (strncmp(s + i, from[k], len) == 0) {
                strcpy(out + w, to[k]);
                w += strlen(to[k]);
                i += len;
                matched = 1;
                break;
            }
        }
        if (!matched) out[w++] = s[i++];
    }
    out[w] = '\0';
}

int main(void) {
    char buf[256], tmp[256];

    // form 1: per-character pairing (a->o; n maps to itself)
    replace_all(buf, "banana", "a", "o");
    printf("%s\n", buf);

    // chained replace: order-sensitive, the 'ab' key never matches
    replace_all(tmp, "ab", "a", "1");
    replace_all(buf, tmp, "ab", "2");
    printf("%s\n", buf);

    // strtr form 2: keys pre-sorted longest first
    const char *from[] = {"ab", "a"};
    const char *to[] = {"2", "1"};
    strtr("ab", from, to, 2, buf);
    printf("%s\n", buf);

    // the classic cascade difference
    replace_all(tmp, "abc", "a", "bb");
    replace_all(buf, tmp, "b", "aa");
    printf("%s\n", buf);

    const char *from2[] = {"a", "b"};
    const char *to2[] = {"bb", "aa"};
    strtr("abc", from2, to2, 2, buf);
    printf("%s\n", buf);
    return 0;
}
Output
bonono
1b
2
aaaaaac
bbaac

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

// literal replace-all helper (chained replacement like str_replace)
std::string replace_all(std::string s, const std::string& from, const std::string& to) {
    size_t pos = 0;
    while ((pos = s.find(from, pos)) != std::string::npos) {
        s.replace(pos, from.size(), to);
        pos += to.size();
    }
    return s;
}

// strtr array form: longest key first, single pass, no rescanning
std::string strtr(const std::string& s, std::vector<std::pair<std::string, std::string>> map) {
    std::sort(map.begin(), map.end(),
              [](const auto& a, const auto& b) { return a.first.size() > b.first.size(); });
    std::string out;
    size_t i = 0;
    while (i < s.size()) {
        bool matched = false;
        for (const auto& [from, to] : map) {
            if (s.compare(i, from.size(), from) == 0) {
                out += to;
                i += from.size();
                matched = true;
                break;
            }
        }
        if (!matched) out += s[i++];
    }
    return out;
}

int main() {
    std::string s = "banana";
    for (char& c : s) {
        if (c == 'a') c = 'o'; // form 1: per-character mapping
    }
    std::cout << s << "\n";

    // chained replace: order-sensitive, the 'ab' key never matches
    std::cout << replace_all(replace_all("ab", "a", "1"), "ab", "2") << "\n";
    std::cout << strtr("ab", {{"a", "1"}, {"ab", "2"}}) << "\n";

    // the classic cascade difference
    std::cout << replace_all(replace_all("abc", "a", "bb"), "b", "aa") << "\n";
    std::cout << strtr("abc", {{"a", "bb"}, {"b", "aa"}}) << "\n";
    return 0;
}
Output
bonono
1b
2
aaaaaac
bbaac

C# v11.0.100

v11.0.100
using System.Text;

// strtr array form: longest key first, single pass, no rescanning
static string StrTr(string s, (string From, string To)[] map)
{
    Array.Sort(map, (a, b) => b.From.Length.CompareTo(a.From.Length));
    var sb = new StringBuilder();
    int i = 0;
    while (i < s.Length)
    {
        bool matched = false;
        foreach (var (from, to) in map)
        {
            if (i + from.Length <= s.Length && s.Substring(i, from.Length) == from)
            {
                sb.Append(to);
                i += from.Length;
                matched = true;
                break;
            }
        }
        if (!matched) { sb.Append(s[i]); i++; }
    }
    return sb.ToString();
}

// form 1 twin: Replace with single chars is the per-character mapping
Console.WriteLine("banana".Replace("a", "o"));
// chained replace: order-sensitive, the 'ab' key never matches
Console.WriteLine("ab".Replace("a", "1").Replace("ab", "2"));
Console.WriteLine(StrTr("ab", new[] { ("a", "1"), ("ab", "2") }));
// the classic cascade difference
Console.WriteLine("abc".Replace("a", "bb").Replace("b", "aa"));
Console.WriteLine(StrTr("abc", new[] { ("a", "bb"), ("b", "aa") }));
Output
bonono
1b
2
aaaaaac
bbaac

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

func main() {
	// form 1: per-character pairing (each rune mapped once, single pass)
	fmt.Println(strings.NewReplacer("a", "o", "n", "n").Replace("banana"))

	// form 2: NewReplacer does single-pass, no-cascade replacement already —
	// but it matches keys in ARGUMENT order, so longer keys must come first
	fmt.Println(strings.NewReplacer("ab", "2", "a", "1").Replace("ab")) // longest first: 2
	fmt.Println(strings.NewReplacer("a", "1", "ab", "2").Replace("ab")) // wrong order: 1b

	// the classic cascade difference: no cascade happens in either language
	fmt.Println(strings.NewReplacer("a", "bb", "b", "aa").Replace("abc"))
}
Output
bonono
2
1b
bbaac

Java v27.0.1

v27.0.1
import java.util.Arrays;

public class Main {
    // strtr array form: longest key first, single pass, no rescanning
    static String strtr(String s, String[][] map) {
        Arrays.sort(map, (a, b) -> b[0].length() - a[0].length());
        StringBuilder sb = new StringBuilder();
        int i = 0;
        outer:
        while (i < s.length()) {
            for (String[] pair : map) {
                if (s.startsWith(pair[0], i)) {
                    sb.append(pair[1]);
                    i += pair[0].length();
                    continue outer;
                }
            }
            sb.append(s.charAt(i++));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // form 1 twin: single-char replace is the per-character mapping
        System.out.println("banana".replace('a', 'o'));
        // chained replace: order-sensitive, the 'ab' key never matches
        System.out.println("ab".replace("a", "1").replace("ab", "2"));
        System.out.println(strtr("ab", new String[][] {{"a", "1"}, {"ab", "2"}}));
        // the classic cascade difference
        System.out.println("abc".replace("a", "bb").replace("b", "aa"));
        System.out.println(strtr("abc", new String[][] {{"a", "bb"}, {"b", "aa"}}));
    }
}
Output
bonono
1b
2
aaaaaac
bbaac

JavaScript v26.13.1

v26.13.1
// form 1: per-character mapping via a lookup table
function strtrChar(s, from, to) {
  const map = {};
  for (let i = 0; i < from.length; i++) map[from[i]] = to[i] ?? ""; // missing tail = delete
  return [...s].map((c) => map[c] !== undefined ? map[c] : c).join("");
}

// form 2: array map, longest key first, single pass (PHP strtr semantics)
function strtr(s, map) {
  const keys = Object.keys(map).sort((a, b) => b.length - a.length);
  let out = "";
  let i = 0;
  outer: while (i < s.length) {
    for (const k of keys) {
      if (s.startsWith(k, i)) {
        out += map[k];
        i += k.length;
        continue outer;
      }
    }
    out += s[i++];
  }
  return out;
}

console.log(strtrChar("banana", "an", "on"));
// chained replace: order-sensitive, the 'ab' key never matches
console.log("ab".replace("a", "1").replace("ab", "2"));
console.log(strtr("ab", { a: "1", ab: "2" }));
// the classic cascade difference
console.log("abc".replaceAll("a", "bb").replaceAll("b", "aa"));
console.log(strtr("abc", { a: "bb", b: "aa" }));
Output
bonono
1b
2
aaaaaac
bbaac

PHP v8.6.0

v8.6.0
// form 1: paired from/to strings, per-character mapping
// ('an' -> 'on' maps a->o and n->n positionally)
echo strtr('banana', 'an', 'on'), "\n";

// form 2: array map — longest key wins, single pass
$map = ['a' => '1', 'ab' => '2'];
echo str_replace(array_keys($map), array_values($map), 'ab'), "\n"; // order-sensitive

echo strtr('ab', $map), "\n"; // longest key wins

// the classic difference: strtr never rescans what it produced
// str_replace's array form chains pair by pair (a->bb, THEN b->aa cascades)
echo str_replace(['a', 'b'], ['bb', 'aa'], 'abc'), "\n";
echo strtr('abc', ['a' => 'bb', 'b' => 'aa']), "\n"; // one pass, no cascade
Output
bonono
1b
2
aaaaaac
bbaac

Python v3.15.2

v3.15.2
# form 1: str.translate is the per-character mapping twin
print("banana".translate(str.maketrans("an", "on")))


def strtr(s, mapping):
    # form 2: longest key first, single pass, no rescanning (PHP strtr)
    keys = sorted(mapping, key=len, reverse=True)
    out, i = "", 0
    while i < len(s):
        for k in keys:
            if s.startswith(k, i):
                out += mapping[k]
                i += len(k)
                break
        else:
            out += s[i]
            i += 1
    return out


# chained replace: order-sensitive, the 'ab' key never matches
print("ab".replace("a", "1").replace("ab", "2"))
print(strtr("ab", {"a": "1", "ab": "2"}))
# the classic cascade difference
print("abc".replace("a", "bb").replace("b", "aa"))
print(strtr("abc", {"a": "bb", "b": "aa"}))
Output
bonono
1b
2
aaaaaac
bbaac

Rust v1.99.1

v1.99.1
// form 1: per-character mapping via a char lookup
fn strtr_char(s: &str, from: &str, to: &str) -> String {
    let pairs: Vec<(char, char)> = from.chars().zip(to.chars()).collect();
    s.chars()
        .map(|c| pairs.iter().find(|(f, _)| *f == c).map_or(c, |&(_, t)| t))
        .collect()
}

// form 2: longest key first, single pass, no rescanning (PHP strtr)
fn strtr(s: &str, map: &[(&str, &str)]) -> String {
    let mut sorted: Vec<&(&str, &str)> = map.iter().collect();
    sorted.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
    let mut out = String::new();
    let mut i = 0usize;
    'outer: while i < s.len() {
        for (from, to) in &sorted {
            if s[i..].starts_with(from) {
                out.push_str(to);
                i += from.len();
                continue 'outer;
            }
        }
        let ch = s[i..].chars().next().unwrap();
        out.push(ch);
        i += ch.len_utf8();
    }
    out
}

fn main() {
    println!("{}", strtr_char("banana", "an", "on"));
    // chained replace: order-sensitive, the 'ab' key never matches
    println!("{}", "ab".replace("a", "1").replace("ab", "2"));
    println!("{}", strtr("ab", &[("a", "1"), ("ab", "2")]));
    // the classic cascade difference
    println!("{}", "abc".replace("a", "bb").replace("b", "aa"));
    println!("{}", strtr("abc", &[("a", "bb"), ("b", "aa")]));
}
Output
bonono
1b
2
aaaaaac
bbaac

TypeScript v26.13.1

v26.13.1
// form 1: per-character mapping via a lookup table
function strtrChar(s: string, from: string, to: string): string {
  const map: Record<string, string> = {};
  for (let i = 0; i < from.length; i++) map[from[i]] = to[i] ?? ""; // missing tail = delete
  return [...s].map((c) => map[c] !== undefined ? map[c] : c).join("");
}

// form 2: array map, longest key first, single pass (PHP strtr semantics)
function strtr(s: string, map: Record<string, string>): string {
  const keys = Object.keys(map).sort((a, b) => b.length - a.length);
  let out = "";
  let i = 0;
  outer: while (i < s.length) {
    for (const k of keys) {
      if (s.startsWith(k, i)) {
        out += map[k];
        i += k.length;
        continue outer;
      }
    }
    out += s[i++];
  }
  return out;
}

console.log(strtrChar("banana", "an", "on"));
// chained replace: order-sensitive, the 'ab' key never matches
console.log("ab".replace("a", "1").replace("ab", "2"));
console.log(strtr("ab", { a: "1", ab: "2" }));
// the classic cascade difference
console.log("abc".replaceAll("a", "bb").replaceAll("b", "aa"));
console.log(strtr("abc", { a: "bb", b: "aa" }));
Output
bonono
1b
2
aaaaaac
bbaac

Language differences

C: no built-in API — the char form is a hand-written mapping loop, the array form a hand-written sorted-keys single pass (the snippet approximates form 1 with single-char replace_all).

C++: no built-in API — hand-write a replace_all helper for chained replacement and a strtr (sort + compare single pass).

C#: single-char string.Replace approximates form 1; the array form is hand-written (the StrTr helper).

Go: strings.NewReplacer is strtr semantics — single pass, no cascading; but it matches in argument order, not longest-first, so longer keys must be listed first; forms 1 and 2 share the same API in Go.

Java: single-char String.replace approximates form 1; the array form is hand-written (the strtr helper, using startsWith(prefix, offset) to match at any position).

JavaScript: no built-in — form 1 via a lookup map, form 2 via sorted keys + startsWith(k, i) in a single pass (fully implemented in the snippet; TS reuses it verbatim).

PHP: the two forms have completely different semantics — the two-string form pairs by position (strtr('banana', 'an', 'on') maps a→o and n→n; when to is shorter than from, the extra chars map to deletion); the array form is longest-key-first, single pass, and never rescans its own output. The classic contrast with str_replace: its array form chains pair by pair ('abc' → a→bb gives 'bbbc', then b→aa replaces the freshly-made bb too → aaaaaac), and it is first-come-first-served (['a'=>'1','ab'=>'2'] runs 'a' first, so the 'ab' key never matches → 1b); strtr matches all keys in one traversal without interference → 2 and bbaac.

Python: str.translate + str.maketrans is form 1's twin (per-character mapping); form 2 is hand-written (the strtr helper, with the for/else construct); chained str.replace for the contrast.

Rust: no built-in — form 1 via a chars().zip lookup, form 2 via sorted keys + starts_with in a single pass (pure std, fully implemented).

TypeScript: same as JS.