Using PHP strtr() Function for String Replacement
This article explains the PHP strtr() function, detailing its syntax and demonstrating four usage patterns—simple character replacement, multiple replacements, sequence replacements, and partial replacements—through clear code examples that illustrate how to substitute or remove substrings efficiently.
In PHP programming, the strtr() function is a versatile string replacement tool that substitutes specified characters or substrings with others.
Basic Syntax of strtr() Function
<code>strtr(string $str, array $replace)</code>Here $str is the original string to be processed, and $replace is an array of characters or strings to replace. $replace can be an associative array where each key is the substring to be replaced and the value is the replacement.
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 each target substring to its replacement.
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>In this example, characters "a" and "r" are removed from the string.
The strtr() function is a powerful PHP string replacement tool that can perform simple character swaps, multiple replacements, sequence replacements, and partial replacements, making string manipulation more convenient and flexible.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.