PHP Tutorial PHP Advanced PHP Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

PHP - String strtr() Function



The PHP String strtr() function returns a string which is the replaced version of the specified string. This function has two versions. The first version is used to replace a set of characters with another set of characters. The second version is used to replace a set of substrings with another set of substrings.

Please note that it does not change the original string and only returns the replaced version of the given string.

Syntax

//version 1
strtr(string, from, to)

//version 2
strtr(string, array)

Parameters

string Required. Specify the string to search.
from Required. Specify what characters to change.
to Required. Specify what characters to change into.
array Required. Specify an associative with keys as what substring to change and values as what substring to change into.

Return Value

Returns a replaced version of the specified string.

Example:

In the example below, every occurrence of 'p' in MyString is replaced by 'o' and similarly every occurrence of 'k' is replaced by 'l'.

<?php
$MyString = "Hekkp Wprkd";

$NewString = strtr($MyString, "pk", "ol");
echo $NewString;
?>

The output of the above code will be:

Hello World

Example:

In the example below, every occurrence of "Hello" in MyString is replaced by "Hi" and similarly every occurrence of "World" is replaced by "PHP".

<?php
$MyString = "Hello World";
$replace = array("Hello" => "Hi", "World" => "PHP");

$NewString = strtr($MyString, $replace);
echo $NewString;
?>

The output of the above code will be:

Hi PHP

❮ PHP String functions

5