This article introduces the strtr string replacement in PHP. Friends who need to learn can refer to this article in detail.
strtr(string,from,to)
Or strtr(string,array)
First, focus on the first method of strtr function
Let’s take a look at the following example:
The code is as follows | Copy code | ||||
?> 1 I lOve yOu |
代码如下 | 复制代码 |
echo strtr("I Love you","Love",""); 结果是 I Love you |
1.strtr It is case sensitive
2. The replacement of strtr is very special. Pay attention to the yOu at the back. The O in the middle is replaced. This is obviously not our intention
Give another special example to illustrate the weirdness of this php sttr function
The code is as follows | Copy code | ||||
?>
|
Another example of another case of strtr function
The code is as follows | Copy code | ||||
echo strtr("I Loves you","Love","lOvEA"); ?>
|
Note that A in the third parameter does not appear in the result
4. I don’t recommend using strtr to exchange less for more
代码如下 | 复制代码 |
$table_change = array('you'=>'her sister'); |
The code is as follows | Copy code |
$table_change = array('you'=>'her sister'); echo strtr("I Love you",$table_change); ?> |
The code is as follows | Copy code |
$table_change = array('you'=>'her sister'); $table_change += array('Love' => 'hate'); echo strtr("I Love you",$table_change); ?> |
The result is
I hate her sister
Remind me again that writing Love as love will not work.
Okay, I talked about it in a messy way. In fact, what I want to say most about strtr is the usage behind it
Simple and convenient.
It seems that the later usage also ignores the problem of different character lengths before and after
The above PHP strtr function experiment, PHP5.2 test passed.
The code is as follows | Copy code | ||||
//The output at this time is baicai instead of bai123cai, because str("pao")
?> |
代码如下 | 复制代码 |
//这个时候输出的为laocai而不是lacai,因为str("pao")>strlen("la") |
Example 2: When the length of the replaced value is smaller than the replaced target
The code is as follows | Copy code | ||||
//The output at this time is laocai instead of lacai, because str("pao")>strlen("la")
echo strtr("paocai!","pao","la");
|
代码如下 | 复制代码 |
echo str_replace("you","paocai","I love you!"); //会输出I love paocai! ?> |
Example 3: Support array replacement
The code is as follows | Copy code |
The code is as follows | Copy code |
echo str_replace("you","paocai","I love you!"); //will output I love paocai!
?>
|