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