PHP | strtr()函数

这个 strtr() 是PHP中的一个内置函数,用于将字符串中的子字符串替换为给定的字符串。它还可以选择将特定单词更改为字符串中的不同单词。该函数区分大小写。 语法:

null
strtr($string, $string1, $string2) or,strtr($string, $arr)

参数: 此函数接受三个参数,如上述语法所示,如下所述:

  1. $string: 它指定要在其中进行替换的字符串。这是一个强制性参数。
  2. $1: 它指定了一个字符串,如果字符串中存在,则必须替换该字符串 $string 。如果未使用数组,则此参数为必填参数。
  3. $2: 它指定的字符所对应的字符串 $1 是要改变的。如果未使用数组,则这是一个强制参数。
  4. $arr: 我们两个都可以通过( $1 $2 )或者 $array 作为参数。当我们想要更改任何特定的子字符串时,数组被作为参数传递。这个 $array 包含要更改的字符串和要更改的字符串。

注: 什么时候 $1 $2 如果长度不同,则较长的字符串将被格式化为较短字符串的长度。 返回值: 此函数的返回值取决于两种情况:

  • 什么时候 $1 $2 作为参数传递,它通过更改 $1 人物 $2 角色。
  • 如果 $array 作为参数传递,它通过将键字符串更改为值字符串来返回转换后的字符串。如果任何键作为“”传递,则它将返回false作为输出。

例如:

Input : $string = "gieuz foh geeks",         $string1 = "iuzh"   ,    $string2="eksr"Output : geeks for geeksExplanation : i replaced by e u replaced by k z replaced by s h replaced by r Input : $string = "gieuz foh geeks",        $string1 = "iuzh"   ,   $string2 = "eks"Output : geeks foh geeks Explanation: "iuzh" was reduced to "iuz" and then replacement was done.  Input: $string = "giiks in giiks",       $arr = array("giiks" => "geeks", "in" => "for")Output: geeks for geeks  Explanation: "giiks" was replaced by "geeks" and "in" by "for" 

下面的程序演示了PHP中的strtr()函数: 项目1: 当传递相同长度的string1和string2时,用于演示strtr()函数的程序。

php

<?php
// PHP program to demonstrate the strtr() function
// when same length string1 and string2 is passed
$string = "gieuz foh geeks" ;
$string1 = "iuzh";
$string2 = "eksr";
// replacement is done
echo strtr ( $string , $string1 , $string2 );
?>


输出:

geeks for geeks

项目2: 当传递不同长度的string1和string2时,用于演示strtr()函数的程序。

php

<?php
// PHP program to demonstrate the strtr() function
// when different length string1 and string2 is passed
$string = "gieuz foh geeks" ;
$string1 = "iuzh";
$string2 = "eks";
// replacement is done
echo strtr ( $string , $string1 , $string2 );
?>


输出:

geeks foh geeks

方案3: 程序来演示strtr()函数,该函数替换存在字符的所有位置。

php

<?php
// PHP program to demonstrate the strtr() function
// which replaces at all positions where
// characters are present
$string = "giiks for giiks" ;
$string1 = "i";
$string2 = "e";
// replacement is done
echo strtr ( $string , $string1 , $string2 );
?>


输出:

geeks for geeks

方案4: 当数组作为参数传递时,用于演示strtr()函数的程序。

php

<?php
// PHP program to demonstrate the strtr() function
// when array is passed as the parameter
$string = "giiks in giiks" ;
$arr = array ("giiks" => "geeks", "in" => " for ");
// replacement is done
echo strtr ( $string , $arr );
?>


输出:

geeks for geeks

方案5: 当数组中的一个键作为“”传递时,用于演示strtr()函数的程序。

php

<?php
// PHP program to demonstrate the strtr() function
// when one key in array is passed as ""
$string = "giiks in giiks" ;
$arr = array ("giiks" => "geeks", "" => " for ");
// replacement is done
echo strtr ( $string , $arr );
?>


输出:

No Output

参考 : http://php.net/manual/en/function.strtr.php

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享