Here we will learn how to replace all the letters of a string by any wild character except the first and the last one with the help of the following string function in php.
strlen(string) : This function returns the length of the string if successful else it will retrun 0.It has one parameter which is mandatory.
For Example:
<?php
echo strlen("Goodmorning");
?>
Output: 11
str_repeat(string,repeat): This function will help in returning the same letter the number of time we need. This function consists of 2 parameters both are mandatory as the first parameter defines the string that is to be repeated and the second function defines the string repeatation number.
For Example:
<?php
echo str_repeat("*",9);
?>
Output: *********
substr(string,start,length): This function returns the extracted portion of the string.This function consists of three parameters. First parameter specifics from which string we need to extract a sub string. Second parameter specifies from which letter of string which should start , this parameter can take 3 values.
1) +ve number specifies a position of a letter from the left hand side of the string.
2) -ve number specifies a position of a letter from the right hand side or end of the string.
3) zero specifies that we should start from the first letter of the string.
The third parameter is optional that specifies the length of the returned string. The default length returned is to the end of the string.
For Example:
<?php
echo substr("Goodmorning",4,-1);
echo substr("Goodmorning",10,1);
?>
Output: morning
Output: g
For Example let us say we want to replace all the letters of the string “Goodmorning” by wildcard character “*” except the first “G” and the last “g”.
<?php
$str = "Goodmorning";
$len = strlen($str); // The string length is 11
substr($str, 0,1); // Here we will start from the first letter (second parameter's value is
//0), and third parameter's value is 1 i.e. end with the second letter.
str_repeat('*',$len - 2); //Here we will repeat the wild character ($len-2) times
substr($str, $len - 1 ,1); //Here we will start from the letter at the position ($len-1 i.e.
//11-1 = 10th letter is n)(second parameter's value is: $len-1),
// and third parameter's value is 1 i.e. end with the second letter
//(from the start letter i.e. 'n' ) which now will be 'g'.
?>
Output: G*********g
0 Comment(s)