Backend Development 4 min read

Using PHP strtr() Function for Flexible String Replacement

This article explains the PHP strtr() function, its syntax, parameter options, and demonstrates several practical examples—including simple character swaps, multiple replacements, sequence replacements, and partial removals—showcasing how to efficiently perform string substitution in backend development.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP strtr() Function for Flexible String Replacement

In PHP programming, the strtr() function is a powerful string‑replacement utility that substitutes specified characters or substrings within a source string with alternative values.

The basic syntax is:

strtr(string $str, array $replace)

Here $str is the original string to be processed, and $replace is either an associative or indexed array where each key/value pair defines a target and its replacement.

Common usage scenarios include:

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

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

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

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

In summary, strtr() provides a concise and flexible way to perform various string‑replacement tasks in PHP, making it especially useful for backend developers handling text manipulation.

BackendprogrammingPHPTutorialstring replacementstrtr
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

login 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.