Backend Development 4 min read

Using PHP strtr() Function for String Replacement

This article explains the PHP strtr() function, detailing its syntax and demonstrating various replacement scenarios—including simple character swaps, multiple replacements, sequence substitutions, and partial removals—through clear code examples and shows how it can be applied in practical string manipulation tasks.

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

In PHP programming, the strtr() function is a powerful string replacement tool that substitutes specified characters or substrings within a string with other characters or substrings.

The basic syntax is strtr(string $str, array $replace) , where $str is the original string and $replace is an associative or indexed array defining the mappings.

The $replace parameter can be an associative array where each key is the target substring and each value is the replacement.

Below are common usage scenarios demonstrating different ways to employ strtr() :

1. Simple character replacement

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

This replaces the substring "World" with "PHP" in the given string.

2. Replacing 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 an associative array maps several substrings to their replacements.

3. Replacing character sequences

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

This swaps the words "PHP" and "programming" with "Java" and "coding" respectively.

4. Partial character replacement

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

By mapping single characters to empty strings, specific characters are removed from the original text.

In summary, strtr() is a versatile PHP function for string manipulation, supporting simple swaps, multiple replacements, sequence substitutions, and partial removals, making it convenient for a wide range of text processing tasks.

Backendcode examplesstring 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.