PHPのお勉強!

PHP TOP

strtr

(PHP 4, PHP 5, PHP 7, PHP 8)

strtr文字の変換あるいは部分文字列の置換を行う

説明

strtr(string $string, string $from, string $to): string

代替のシグネチャ (名前付き引数をサポートしていません):

strtr(string $string, array $replace_pairs): string

引数を三つ渡した場合、この関数は string のコピーを返します。その際に、文字列中に from の各文字 (シングルバイト) があれば to の対応する文字に変換します。つまり、すべての $from[$n]$to[$n] に置換されることになります。ここで $n は、どちらの引数でも共通に有効なオフセットです。

fromto の長さが異なる場合、長い方の余分な文字は無視されます。 返される文字列の長さは、もとの string と同じになります。

引数を二つだけ渡す場合は、二番目の引数を array('from' => 'to', ...) 形式の配列にしなければなりません。 返される値は文字列で、もとの文字列中にある配列のキーと同じ部分を対応する値で置換したものとなります。 一番長いキーから順に調べます。一度部分文字列の置換を行うと、 置換後の文字列がさらに置換の対象となることはありません。

この場合は、配列のキーと値は任意の長さにすることができますが、キーを空にすることだけはできません。 さらに、返される文字列の長さはもとの string とは異なる可能性があります。 しかし、この関数が最も効率的に働くのは、すべてのキーが同じ長さである場合です。

パラメータ

string

変換する文字列。

from

to に変換される文字列。

to

from を置換する文字列。

replace_pairs

replace_pairs パラメータを tofrom のかわりに使用することができます。この場合は array('from' => 'to', ...) 形式の配列となります。

replace_pairs の中に空文字列 ("") のキーがある場合は、その要素は無視されます。 PHP 8.0.0 以降では、この場合 E_WARNING が発生します。

戻り値

変換後の文字列を返します。

例1 strtr() の例

<?php
// この形式の場合、strtr() はバイト単位での変換を行います。
// したがって、ここではシングルバイトエンコーディングを想定しています。
$addr = strtr($addr, "äåö", "aao");
?>

次の例は、引数を二つだけ指定して strtr() をコールしたときの挙動を示すものです。置換の優先度 ("h" よりもっと長いキーに一致しているので、この置換は行われていないこと)、 そして一度置換した文字列はもう置換の対象にならないことを確認しましょう。

例2 2 つの引数を伴う strtr() の例

<?php
$trans
= array("h" => "-", "hello" => "hi", "hi" => "hello");
echo
strtr("hi all, I said hello", $trans);
?>

上の例の出力は以下となります。

hello all, I said hi

これらふたつのモードの挙動は大きく異なります。引数が三つの場合は strtr() はバイト単位で置換し、二つの場合はより長い部分文字列を置換します。

例3 strtr() の挙動の比較

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo
strtr("baab", $trans);
?>

上の例の出力は以下となります。

1001
ba01

参考

  • str_replace() - 検索文字列に一致したすべての文字列を置換する
  • preg_replace() - 正規表現検索および置換を行う

add a note

User Contributed Notes 32 notes

up
118
evan dot king at NOSPAM dot example dot com
9 years ago
Here's an important real-world example use-case for strtr where str_replace will not work or will introduce obscure bugs:

<?php

$strTemplate
= "My name is :name, not :name2.";
$strParams = [
':name' => 'Dave',
'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
':name2' => 'Steve',
':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
];

echo
strtr($strTemplate, $strParams);
// "My name is Dave, not Steve."

echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
// "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."

?>

Any time you're trying to template out a string and don't necessarily know what the replacement keys/values will be (or fully understand the implications of and control their content and order), str_replace will introduce the potential to incorrectly match your keys because it does not expand the longest keys first.

Further, str_replace will replace in previous replacements, introducing potential for unintended nested expansions. Doing so can put the wrong data into the "sub-template" or even give users a chance to provide input that exposes data (if they get to define some of the replacement strings).

Don't support recursive expansion unless you need it and know it will be safe. When you do support it, do so explicitly by repeating strtr calls until no more expansions are occurring or a sane iteration limit is reached, so that the results never implicitly depend on order of your replacement keys. Also make certain that any user input will expanded in an isolated step after any sensitive data is already expanded into the output and no longer available as input.

Note: using some character(s) around your keys to designate them also reduces the possibility of unintended mangling of output, whether maliciously triggered or otherwise. Thus the use of a colon prefix in these examples, which you can easily enforce when accepting replacement input to your templating/translation system.
up
63
Hayley Watson
11 years ago
Since strtr (like PHP's other string functions) treats strings as a sequence of bytes, and since UTF-8 and other multibyte encodings use - by definition - more than one byte for at least some characters, the three-string form is likely to have problems. Use the associative array form to specify the mapping.

<?php
// Assuming UTF-8
$str = 'Äbc Äbc'; // strtr() sees this as nine bytes (including two for each Ä)
echo strtr($str, 'Ä', 'a'); // The second argument is equivalent to the string "\xc3\x84" so "\xc3" gets replaced by "a" and the "\x84" is ignored

echo strtr($str, array('Ä' => 'a')); // Works much better
?>
up
19
allixsenos at gmail dot com
15 years ago
fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...

also, renamed to normalize()

<?php

function normalize ($string) {
$table = array(
'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
);

return
strtr($string, $table);
}

?>
up
5
horak.jan AT centrum.cz
17 years ago
Here is a function to convert middle-european windows charset (cp1250) to the charset, that php script is written in:

<?php
function cp1250_to_utf2($text){
$dict = array(chr(225) => 'á', chr(228) => 'ä', chr(232) => 'č', chr(239) => 'ď',
chr(233) => 'é', chr(236) => 'ě', chr(237) => 'í', chr(229) => 'ĺ', chr(229) => 'ľ',
chr(242) => 'ň', chr(244) => 'ô', chr(243) => 'ó', chr(154) => 'š', chr(248) => 'ř',
chr(250) => 'ú', chr(249) => 'ů', chr(157) => 'ť', chr(253) => 'ý', chr(158) => 'ž',
chr(193) => 'Á', chr(196) => 'Ä', chr(200) => 'Č', chr(207) => 'Ď', chr(201) => 'É',
chr(204) => 'Ě', chr(205) => 'Í', chr(197) => 'Ĺ', chr(188) => 'Ľ', chr(210) => 'Ň',
chr(212) => 'Ô', chr(211) => 'Ó', chr(138) => 'Š', chr(216) => 'Ř', chr(218) => 'Ú',
chr(217) => 'Ů', chr(141) => 'Ť', chr(221) => 'Ý', chr(142) => 'Ž',
chr(150) => '-');
return
strtr($text, $dict);
}
?>
up
6
Annubis
6 years ago
Since I was having a lot of trouble finding a multibyte safe strtr and the solutions I found didn't help, I came out with this function, I don't know how it works with non latin chars but it works for me using spanish/french utf8, I hope it helps someone...
<?php
if(!function_exists('mb_strtr')) {
function
mb_strtr ($str, $from, $to = null) {
if(
is_array($from)) {
$from = array_map('utf8_decode', $from);
$from = array_map('utf8_decode', array_flip ($from));
return
utf8_encode (strtr (utf8_decode ($str), array_flip ($from)));
}
return
utf8_encode (strtr (utf8_decode ($str), utf8_decode($from), utf8_decode ($to)));
}
}
?>
up
8
Michael Schuijff
13 years ago
I found that this approach is often faster than strtr() and won't change the same thing in your string twice (as opposed to str_replace(), which will overwrite things in the order of the array you feed it with):

<?php
function replace ($text, $replace) {
$keys = array_keys($replace);
$length = array_combine($keys, array_map('strlen', $keys));
arsort($length);

$array[] = $text;
$count = 1;
reset($length);
while (
$key = key($length)) {
if (
strpos($text, $key) !== false) {
for (
$i = 0; $i < $count; $i += 2) {
if ((
$pos = strpos($array[$i], $key)) === false) continue;
array_splice($array, $i, 1, array(substr($array[$i], 0, $pos), $replace[$key], substr($array[$i], $pos + strlen($key))));
$count += 2;
}
}
next($length);
}
return
implode($array);
}
?>
up
12
dot dot dot dot dot alexander at gmail dot com
16 years ago
OK, I debugged the function (had some errors)
Here it is:

if(!function_exists("stritr")){
function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
if( is_string( $one ) ){
$two = strval( $two );
$one = substr( $one, 0, min( strlen($one), strlen($two) ) );
$two = substr( $two, 0, min( strlen($one), strlen($two) ) );
$product = strtr( $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two ) );
return $product;
}
else if( is_array( $one ) ){
$pos1 = 0;
$product = $string;
while( count( $one ) > 0 ){
$positions = array();
foreach( $one as $from => $to ){
if( ( $pos2 = stripos( $product, $from, $pos1 ) ) === FALSE ){
unset( $one[ $from ] );
}
else{
$positions[ $from ] = $pos2;
}
}
if( count( $one ) <= 0 )break;
$winner = min( $positions );
$key = array_search( $winner, $positions );
$product = ( substr( $product, 0, $winner ) . $one[$key] . substr( $product, ( $winner + strlen($key) ) ) );
$pos1 = ( $winner + strlen( $one[$key] ) );
}
return $product;
}
else{
return $string;
}
}/* endfunction stritr */
}/* endfunction exists stritr */
up
5
elloromtz at gmail dot com
14 years ago
If you supply 3 arguments and the 2nd is an array, strtr will search the "A" from "Array" (because you're treating it as a scalar string) and replace it with the 3rd argument:

strtr('Analogy', array('x'=>'y'), '_'); //'_nalogy'

so in reality the above code has the same affect as:

strtr('Analogy', 'A' , '_');
up
6
dcz at phpbb-seo dot com
11 years ago
strstr will issue a notice when $replace_pairs contains an array, even unused, with php 5.5.0.

It was not the case with version at least up to 5.3.2, but I'm not sure the notice was added with exactly 5.5.0.

<?php
$str
= 'hi all, I said hello';
$replace_pairs = array(
'all' => 'everybody',
'unused' => array('somtehing', 'something else'),
'hello' => 'hey',
);
// php 5.5.0 Notice: Array to string conversion in test.php on line 8
echo strtr($str, $replace_pairs); // hi everybody, I said hey
?>

since the result is still correct, @strstr seems a working solution.
up
6
Tedy
12 years ago
Since strtr() is twice faster than strlwr I decided to write my own lowering function which also handles UTF-8 characters.

<?php

function strlwr($string, $utf = 1)
{
$latin_letters = array('Ă' => 'a',
'Â' => 'a',
'Î' => 'i',
'Ș' => 's',
'Ş' => 's',
'Ț' => 't',
'Ţ' => 't');

$utf_letters = array('Ă' => 'ă',
'Â' => 'â',
'Î' => 'î',
'Ș' => 'ș',
'Ş' => 'ş',
'Ț' => 'ț',
'Ţ' => 'ţ');

$letters = array('A' => 'a',
'B' => 'b',
'C' => 'c',
'D' => 'd',
'E' => 'e',
'F' => 'f',
'G' => 'g',
'H' => 'h',
'I' => 'i',
'J' => 'j',
'K' => 'k',
'L' => 'l',
'M' => 'm',
'N' => 'n',
'O' => 'o',
'P' => 'p',
'Q' => 'q',
'R' => 'r',
'S' => 's',
'T' => 't',
'U' => 'u',
'V' => 'v',
'W' => 'w',
'X' => 'x',
'Y' => 'y',
'Z' => 'z');

return (
$utf == 1) ? strtr($string, array_merge($utf_letters, $letters)) : strtr($string, array_merge($latin_letters, $letters));
}

?>

This allows you to lower every character (even UTF-8 ones) if you don't set the second parameter, or just lower the UTF-8 ones into their specific latin characters (used when making friendly-urls for example).

I used romanian characters but, of course, you can add your own local characters.

Feel free to use/modify this function as you wish. Hope it helps.
up
4
troelskn at gmail dot com
16 years ago
Here's another transcribe function. This one converts cp1252 (aka. Windows-1252) into iso-8859-1 (aka. latin1, the default PHP charset). It only transcribes the few exotic characters, which are unique to cp1252.

function transcribe_cp1252_to_latin1($cp1252) {
return strtr(
$cp1252,
array(
"\x80" => "e", "\x81" => " ", "\x82" => "'", "\x83" => 'f',
"\x84" => '"', "\x85" => "...", "\x86" => "+", "\x87" => "#",
"\x88" => "^", "\x89" => "0/00", "\x8A" => "S", "\x8B" => "<",
"\x8C" => "OE", "\x8D" => " ", "\x8E" => "Z", "\x8F" => " ",
"\x90" => " ", "\x91" => "`", "\x92" => "'", "\x93" => '"',
"\x94" => '"', "\x95" => "*", "\x96" => "-", "\x97" => "--",
"\x98" => "~", "\x99" => "(TM)", "\x9A" => "s", "\x9B" => ">",
"\x9C" => "oe", "\x9D" => " ", "\x9E" => "z", "\x9F" => "Y"));
up
4
martin[dot]pelikan[at]gmail[dot]com
18 years ago
// if you are upset with windows' ^M characters at the end of the line,
// these two lines are for you:
$trans = array("\x0D" => "");
$text = strtr($orig_text,$trans);

// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
up
5
Sidney Ricardo
16 years ago
This work fine to me:

<?php
function normaliza ($string){
$a = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ
ßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ'
;
$b = 'aaaaaaaceeeeiiiidnoooooouuuuy
bsaaaaaaaceeeeiiiidnoooooouuuyybyRr'
;
$string = utf8_decode($string);
$string = strtr($string, utf8_decode($a), $b);
$string = strtolower($string);
return
utf8_encode($string);
}
?>
up
4
dot dot dot dot dot alexander at gmail dot com
16 years ago
Here is the stritr I always needed... I wrote it in 15 minutes... But only after the idea struck me. Hope you find it helpful, and enjoy...
<?php
if(!function_exists("stritr")){
function
stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
if( is_string( $one ) ){
$two = strval( $two );
$one = substr( $one, 0, min( strlen($one), strlen($two) ) );
$two = substr( $two, 0, min( strlen($one), strlen($two) ) );
$product = strtr( $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two ) );
return
$product;
}
else if(
is_array( $one ) ){
$pos1 = 0;
$product = $string;
while(
count( $one ) > 0 ){
$positions = array();
foreach(
$one as $from => $to ){
if( (
$pos2 = stripos( $product, $from, $pos1 ) ) === FALSE ){
unset(
$one[ $from ] );
}
else{
$positions[ $from ] = $pos2;
}
}
$winner = min( $positions );
$key = array_search( $winner, $positions );
$product = ( substr( $product, 0, $winner ) . $positions[$key] . substr( $product, ( $winner + strlen($key) ) ) );
$pos1 = ( $winner + strlen( $positions[$key] ) );
}
return
$product;
}
else{
return
$string;
}
}
/* endfunction stritr */
}/* endfunction exists stritr */
?>
up
3
doydoy44
11 years ago
The example of VOVA (http://www.php.net/manual/fr/function.strtr.php#111968) is good but the result is false:
His example dont replace the string.

<?php
function f1_strtr() {
for(
$i=0; $i<1000000; ++$i) {
$new_string = strtr("aboutdealers.com", array(".com" => ""));
}
return
$new_string;
}
function
f2_str_replace() {
for(
$i=0; $i<1000000; ++$i) {
$new_string = str_replace( ".com", "", "aboutdealers.com");
}
return
$new_string;
}
$start = microtime(true);
$strtr = f1_strtr();
$stop = microtime(true);
$time_strtr = $stop - $start;

$start = microtime(true);
$str_replace = f2_str_replace();
$stop = microtime(true);
$time_str_replace = $stop - $start;


echo
'time strtr : ' . $time_strtr . "\tresult :" . $strtr . "\n";
echo
'time str_replace : ' . $time_str_replace . "\tresult :" . $str_replace . "\n";
echo
'time strtr > time str_replace => ' . ($time_strtr > $time_str_replace);
?>
--------------------------------------
time strtr : 3.9719619750977 result :aboutdealers
time str_replace : 2.9930369853973 result :aboutdealers
time strtr > time str_replace => 1

str_replace is faster than strtr
up
3