Master PHP’s strtr(): Simple, Multi‑Replace, and Partial String Substitutions

This article explains PHP's strtr() function, covering its syntax, how to perform simple character swaps, multiple replacements, sequence substitutions, and partial replacements, and provides clear code examples for each use case.

php Courses
php Courses
php Courses
Master PHP’s strtr(): Simple, Multi‑Replace, and Partial String Substitutions

In PHP programming, the strtr() function is a useful string replacement function that replaces specified characters or substrings with others. This article introduces its usage and provides concrete code examples.

The basic syntax is: strtr(string $str, array $replace) Here $str is the original string, and $replace is an array of characters or strings to replace. The $replace parameter can be an associative or indexed array where each key/value pair represents the target and replacement.

Common use cases:

1. Simple character replacement

$text = "Hello World";
echo strtr($text, "World", "PHP"); // output: Hello PHP

This replaces "World" with "PHP".

2. Replace multiple characters

$text = "I like apples and oranges.";
$replace = array("apples" => "bananas", "oranges" => "grapes");
echo strtr($text, $replace); // output: I like bananas and grapes.

Here $replace is an associative array mapping strings to their replacements.

3. Replace character sequences

$text = "I love PHP programming.";
$replace = array("PHP" => "Java", "programming" => "coding");
echo strtr($text, $replace); // output: I love Java coding.

This swaps "PHP" with "Java" and "programming" with "coding".

4. Partial character replacement

$text = "I am a programmer.";
$replace = array("a" => "", "r" => "");
echo strtr($text, $replace); // output: I m pogamm.

In this example, specific characters are removed by mapping them to empty strings.

Summary

The strtr() function is a powerful tool for string replacement in PHP. It can handle simple character swaps, multiple replacements, sequence substitutions, and partial replacements, making string manipulation more convenient and flexible.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentPHPCode Examplesstring-replacementphp-functionsstrtr
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.