PHP String strtr()函數
strtr()是PHP的內置函數,用于替換字符串中的子字符串。愛掏網 - it200.com它提供了更改字符串中特定單詞的功能。愛掏網 - it200.comstrtr()函數可以翻譯字符或替換子字符串。愛掏網 - it200.com它是 區分大小寫 的函數。愛掏網 - it200.comPHP 4+ 版本支持此函數。愛掏網 - it200.com
注意:strtr()函數會將字符從所有出現的位置替換掉。愛掏網 - it200.com
PHP中還有一些類似strtolower()函數的其他函數:
此函數有兩種語法可用,一種用于字符串或字符替換,另一種用于數組鍵替換。愛掏網 - it200.com這些語法如下。愛掏網 - it200.com
對于字符串替換:
strtr (string str, stringfrom, string $to)
在這個函數中有三個參數。愛掏網 - it200.com它將$from
中的每個字符替換為$to
,并返回$str
的副本。愛掏網 - it200.com
對于數組鍵的替換:
strtr (string str, arrayreplace_pair)
在上面的函數中,包含兩個參數。愛掏網 - it200.com第二個參數$replace_pair
的形式是一個數組(’from’ => ‘to’,?)。愛掏網 - it200.com它將返回一個字符串,其中替換了所有出現的數組鍵與相應值。愛掏網 - it200.com
參數
$str: 這是一個字符串參數,用于被翻譯,意味著它是將被翻譯的主要字符串。愛掏網 - it200.com
$from: 這是此函數的下一個參數,它將在字符串中被$to
替換。愛掏網 - it200.com它是一個 必需的 參數,除非使用數組。愛掏網 - it200.com
$to: 這是一個將用$from
變量替換的參數。愛掏網 - it200.com該參數也是 必需的 ,就像$from
一樣,除非使用數組。愛掏網 - it200.com
注意:如果from和to具有不同長度,則較長字符串的其他字符將被忽略。愛掏網 - it200.com返回的字符串$str
的長度將相同。愛掏網 - it200.com
$replace_pair: 該參數以數組的形式而不是 from 和 to . 此數組包含兩個字符串( $string1 和 $string2 ),即字符串1需要被更改并且將其更改為字符串2。愛掏網 - it200.com
注意:如果string1和string2的長度都不同,則較長字符串將被格式化為較短字符串的長度。愛掏網 - it200.com
返回值
- 它返回替換了
$from
字符為$to
字符的翻譯后的字符串。愛掏網 - it200.com - 如果傳遞的參數是數組(
$replace_pair
),那么它返回通過使用相應的值將鍵字符串更改為的翻譯后的字符串。愛掏網 - it200.com如果該數組參數包含一個空字符串的鍵(? ?),則將返回FALSE。愛掏網 - it200.com
示例
下面給出了一些示例。愛掏網 - it200.com通過這些示例,我們可以了解strtr()函數的工作原理。愛掏網 - it200.com
示例1
<?php
strng1 = "Hiy! Guud Mohneng";from = "yuhe";
to = "eori";
echo strtr(strng1, from,to);
?>
輸出:
Hie! Good Morning
說明
y 被替換為 e
u 被替換為 o
h 被替換為 r
e 被替換為 i
所以, Hiy! Guud Mohneng 被替換為 Hie! Good Morning 。愛掏網 - it200.com
示例 2
PHP 程序演示當 $from
和 $to
長度不同時的 strtr() 函數。愛掏網 - it200.com
<?php
strng1 = "Hiy! Geud Mohning";from = "yeuh";
to = "eor";
echo strtr(strng1, from,to);
?>
輸出結果:
Hie! Gord Mohning
解釋
y被替換成e
e被替換成o
u被替換成r
h不被任何字符替換。愛掏網 - it200.com
現在, Hiy! Geud Mohneng 被替換成 Hie! Gord Mohning 。愛掏網 - it200.com
示例3
用數組鍵進行替換
<?php
strng = "Wilcone to javaCpoint.";arr1 = array("Wilcone" => "Welcome", "javaCpoint" => "javaTpoint");
echo strtr(strng,arr1);
?>
輸出:
Welcome to javaTpoint.
示例4
PHP程序演示了strtr()函數,當數組的鍵為空字符串””時。愛掏網 - it200.com
<?php
strng = "Wilcone to javaCpoint.";arr1 = array("Wilcone" => "Welcome", "" => "javaTpoint");
echo strtr(strng,arr1);
?>
輸出:
No output
示例5
單個字母進行多次替換
<?php
string = "Wilcone to javaCpoint.";from = "inC";
to = "emT";
echo strtr(string, from,to);
?>
輸出:
Welcome to javaTpoemt.
解釋
在多個地方將 i 替換為 e 。愛掏網 - it200.com
在多個地方將 n 替換為 m 。愛掏網 - it200.com
由于此函數區分大小寫,僅將 C 替換為 T 一次。愛掏網 - it200.com
所以, Wilcone to javaCpoint 被替換為 Welcome to javaTpoemt 而不是 Welcome to JavaTpoint 。愛掏網 - it200.com
示例6
區分大小寫
<?php
strng = "Gqqd health Gqqd Life.";from = "q";
to = "o";
echo strtr(strng, from,to);
echo "</br>";
echo strtr($strng, "Q", "o";); //case-sensitive
?>
輸出:
在這個示例中,對于第一個情況,所有出現的 q 都被替換為 o。愛掏網 - it200.com另一方面,Q 沒有被替換為 o,因為它是一個區分大小寫的函數。愛掏網 - it200.com
Good health Good Life.
Gqqd health Gqqd Life. //case-sensitive