We often use the str_replace function to replace characters. Instead, we will use the substr_replace function to replace a character. Let's briefly list the usage of these two examples. We often use the str_replace function to replace characters. Instead, we will use the substr_replace function to replace a character. Let's briefly list the usage of these two examples.
Script ec (2); script
There are two functions to replace a specified string with a PHP string.
Substr_replace (): replace a part of the string with another string.
Str_replace (): use one string to replace other characters in the string.
Substr_replace ()
The substr_replace () function is used to replace a part of a string with another string and return a mixed type.
The Code is as follows: |
|
Echo substr_replace ('abcdef', '###', 1); // output ### Echo substr_replace ('abcdef', '###', 1, 2); // output a ### def Echo substr_replace ('abcdef', '###',-3, 2); // output abc ### ef Echo substr_replace ('abcdef', '###', 1,-2); // output a ### ef ?> |
Str_replace ()
The str_replace () function uses a string to replace other characters in the string and returns the mixed type.
The Code is as follows: |
|
Echo str_replace ("world", "earth", "Hello world! "); // Output Hello earth! // Replace multiple and the second parameter is null Echo str_replace ("o", "", "Hello world! "); // Output Hell wrld! // Use an array $ Arr = array ("e", "o "); $ Arr2 = array ("x", "y "); Echo str_replace ($ arr, $ arr2, "Hello World of PHP", $ I); // output Hxlly Wyrld yf PHP Echo $ I; // output 4 ?> |
Supplement: Method 1:
The Code is as follows: |
|
Header ("content-type: text/html; charset = UTF-8 "); $ Pattern = preg_quote ('fairy '); // automatically add escape characters to special characters \ $ Str = 'Mrs. song is really beautiful '; Echo preg_replace ("/($ pattern)/", "$1", $ str ); ?> |
1. preg_replace ()
The Code is as follows: |
|
$ Msg = preg_replace ("/And the middle part $ Msg = preg_replace ("/<[^>] +>/", "", $ msg); ----- Delete <> and intermediate content |
2. ereg () and eregi ()
Note: The preg_match () function is usually a faster alternative than ereg ().
The Code is as follows: |
|
Eregi (" ] +)> (. +)", $ Data, $ B) ---- check whether the $ data contains the body tag. If yes, assign $ B [0] to the parameter and $ B [1] to the intermediate part. |
Note that the ereg () and eregi () functions are not supported in php5.3 and later versions. Therefore, you 'd better use the preg_replace function.