PHP string replacement methods. In actual programming, the strtr () function is usually used to implement string replacement. The following describes how to replace a PHP string. In actual programming, the strtr () function is usually used to implement string replacement. The following describes how to replace a PHP string.
V first, let's take a look at the two statuses of the PHP string replacement function strtr ().
Strtr (string, from,)
Or strtr (string, array)
First, the first method for strtr functions
Let's take a look at the following PHP string replacement example:
- < ?php
- echo strtr("I Love you
","Lo","lO");
- ?>
The result is:
I lOve yOu
This result reminds us
1. strtr: it is case sensitive.
2. the replacement of strtr is very special. yOu should check that yOu and the Middle O are replaced. this is obviously not our intention.
Here is another special example to show how strange this php sttr function is.
- < ?php
- echo strtr("I Love
you","Love","");
- ?>
The result is
I Love you
PHP string replacement will not change anything, so strtr should note that:
3. cannot be replaced with Null, that is, the last parameter cannot be a null string. of course, spaces are acceptable.
Another example of strtr function
- < ?php
- echo strtr("I Loves you","Love","lOvEA");
- ?>
The result is
I lOvEs yOu
Note that A of the third parameter does not appear in the result.
4. I do not recommend replacing strtr with less
Okay. why should I use this strtr function?
The reason is that it is fast
It is said that strtr is four times faster than str_replace
5. use the strtr function to replace PHP strings.
How can it be used for comfort?
This is the second case.
Strtr (string, array)
6. use strtr as expected
- < ?php
- $table_change = array('you'=>'her sister');
- echo strtr("I Love you",$table_change);
- ?>
-
Result:
I Love her sister
7. tips: If you want to replace the PHP string with the replacement string, add the replacement string to the array.
For example
- < ?php
- $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 is not feasible.
Okay. let's talk about it in a mess. In fact, what strtr wants to talk about is the subsequent usage.
Simple and convenient.
It seems that the subsequent usage also ignores the problem of different front and back character lengths.
The above PHP string replacement experiment, PHP5.2 test passed.
Aggregate () function. The following describes how to replace a PHP string ....