Backend Development 3 min read

Using PHP strtr() Function for Flexible String Replacement

This article explains PHP's strtr() function, detailing its syntax and demonstrating simple character replacement, multiple replacements, sequence replacements, and partial replacements with clear code examples, and discusses using associative arrays for mapping replacements while highlighting its flexibility for various string manipulation tasks.

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

In PHP programming, the strtr() function is a useful string replacement function that replaces specified characters or strings in a string.

strtr() function basic syntax

<code>strtr(string $str, array $replace)</code>

Here, $str is the original string and $replace is the set of characters or strings to replace, which can be an associative or indexed array.

Different usages of strtr()

Simple character replacement

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

This example replaces "World" with "PHP" in the string.

Replacing multiple characters

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

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

Replacing character sequences

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

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

Partial character replacement

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

This example removes specific characters by mapping them to empty strings.

The strtr() function is a powerful tool for flexible string replacement in PHP.

backendPHPstring 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

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.