Home  >  Article  >  Backend Development  >  PHP interception string function strtr/str_replace

PHP interception string function strtr/str_replace

巴扎黑
巴扎黑Original
2016-11-22 16:19:071562browse

/**

* 1. strtr converts the specified characters

*

* string strtr ( string $str , string $from , string $to )

* string strtr ( string $str , array $replace_pairs )

*

* This function returns a copy of str and converts the characters specified in from to the corresponding characters in to.

* If from and to are not equal in length, the extra characters will be ignored.

*/


$str = 'http://flyer0126.iteye.com/';


echo strtr($str, 'IT', 'java');

//output: http://flyer0126.iteye.com/ strtr is case sensitive


//If from and to are not equal in length, the extra characters will be ignored

echo strtr($str , 'it', 'java');

//output: haap://flyer0126.jaeye.com/

//iteye --> jaeye it is only replaced by ja

//http --> ; haap replaces corresponding positions character by character, which does not meet our original intention


echo strtr($str, 'it', '');

//output: http://flyer0126.iteye.com / No replacement


echo strtr($str, 'it', ' ');

//output: http://flyer0126.teye.com/ Can be replaced


/**

* A summary of the from->to method of function strtr:

* 1. Case sensitive;

* 2. When the lengths of form and to are not equal, the extra characters will be ignored, and you cannot replace less with more, or Cannot replace more with less;

* 3. Replace corresponding positions character by character;

* 4. Cannot be replaced with empty space, but can be replaced with spaces.

*/


// In comparison, the latter method is obviously more appropriate

$replace_pairs = array(

'http://'=>'',

'it' = > 'java'

);

echo strtr($str, $replace_pairs);

//output: flyer0126.javaeye.com/ The replacement was successful and in line with the original intention of the replacement


/**

 * 2. 函数 str_replace

 * mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

  */


echo str_replace('it', 'java', $str);

//output: http://flyer0126.javaeye.com/

echo str_replace(array('http', ' :', '//', '/'), '', $str);

//output: flyer0126.iteye.com

echo str_replace(array('http', 'it', '/') , array('https', 'java', ''), $str);

//output: https:flyer0126.javaeye.com


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn