Php strtr
From w3cyberlearnings
Contents |
PHP function strtr
This function translates characters or replace substrings.
Syntax strtr
- string: string to be translated or replaced.
- from: what characters within the string to be changed or replaced
- to: the characters to change into
- array: this the array contains key and value to be changed or replaced. The key is the from and the value is the to.
key=>value equal from=>to.
strtr(string, from, to); OR strtr(string, array);
Example 1
- Replace G=>h
- Replace h=>x
<?php echo strtr("Girl of the world!", "Gw", "hx"); ?>
Output
hirl of the xorld!
Example 2
<?php <?php $str = "My friends are all welcome to my new place"; $arry = array('My' => 'Your', 'friends' => 'teachers', 'new' => 'old', 'my'=>'your' ); $new_str = strtr($str,$arry); echo $new_str; ?>
Output
Your teachers are all welcome to your old place
Example 3: Using strstr to make the guessing word game
- Try to replace in each character with "_" so that user can make a guess game.
- This game will display different missing word each time you refresh the page.
<?php $word_list = array( 'girl', 'body', 'fish', 'dog', 'lovely', 'wish' ); $word_select = array(); foreach ($word_list as $k) { $random_indx = rand(1, 3); $tmp_str = substr($k, $random_indx); $word_select[] = strtr($k, $tmp_str, '_'); } print_r($word_select); ?>
Output
Array ( [0] => g_rl [1] => bo_y [2] => fis_ [3] => do_ [4] => lo_ely [5] => wi_h )