Hướng dẫn
Quảng cáo

Hàm strtr() trong PHP

Hướng dẫn cách sử dụng hàm strtr() trong lập trình PHP

Tác dụng của hàm strtr()

The strtr() function translate characters or replace substrings within a string.

The following table summarizes the technical details of this function.

Return Value: Returns the translated string. If the array parameter contains a key which is an empty string (""), FALSE will be returned.
Version: PHP 4+

Syntax

The basic syntax of the strtr() function is given with:

strtr(string, from, to); -Or- strtr(string, array);

The following example shows the strtr() function in action.

<?php
// Sample string
$str = "Mary had a little lamb";

// Performing replacement
echo strtr($str, "My", "Sa");
?>

If from and to have different lengths, the extra characters in the longer of the two are ignored, which means the length of the resulting string will remain the same.

You can alternatively use an array instead of from and to parameters. In this case, the keys and the values may have any length, provided that there is no empty key; additionally, the length of the resulting string may differ from the original string. Here's an example:

<?php
// Sample string
$str = "hi all, I said hello";

// Defining replacement pairs
$replace_array = array("h" => "x", "hi" => "hello", "hello" => "hi");

// Performing replacement
echo strtr($str, $replace_array);
?>

If you see the output of the above example you will notice "h" is not picked by this function because there are longer matches available. Also, the replaced text was not searched again.


Parameters

The strtr() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to translate.
from Required. Specifies the characters or substring to be replaced.
to Required. Specifies the replacement substring.
array Required (unless from and to is used). Specifies an array in the form array("from" => "to", ...). This parameter can be used instead of from and to.

More Examples

Here're some more examples showing how strtr() function actually works:

This function behaves differently in two and three arguments modes. With three arguments, strtr() will replace characters; whereas with two, it may replace longer substrings.

<?php
// Sample string
$str = "woow";

// Defining replacement pairs
$replace_array = array("wo" => "x1");

// Performing replacement
echo strtr($str, "wo", "x1")."<br>";
echo strtr($str, $replace_array);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements