function str2_in_str1($str1, $str2) {
$p_len = strlen($str2);
$w_len = strlen($str1);
$w_start = $w_len-$p_len;
if (substr($str1, $w_len-$p_len, $p_len) == $str2) {
return "true";
}
else
{
return "false";
}
}
echo str2_in_str1("Python","thon")."
";
echo str2_in_str1("JavaScript","ript")."
";
can someone explain to me what happened in this function?? Thanks.
It check that the $str2
is in the end of $str1
or not. also return a true
or false
for this comparison.
Even though this can be done cleaner... It's a good idea when learning to go through and give your variables descriptive names and add in a few comments.
Which I have done here in hope that it might make what is going on clearer.
So I have broken this down into more digestible sections and commented it...
NOTE: There are better ways to perform this same function...
/**
* Determine if String2 matches the end of String 1
*
* Example: String1 Python
* String2 __thon
* would return true, otherwise false
*
* @param $string1
* @param $string2
* @return string
*/
function is_str2_at_end_of_str1($string1, $string2) {
$length_of_string1 = strlen($string1);
$length_of_string2 = strlen($string2);
// Get the position of where string2
// Only works if $length_string1 > $length_string2
$position_in_string1 = $length_of_string1 - $length_of_string2;
// Get the characters at the end of string1 that is the same size as string2.
// Go to php.net and look up substr()
$string1_end_section = substr($string1, $position_in_string1, $length_of_string2);
if ($string1_end_section == $string2) {
return "true"; // This is a string and not a boolean true/false
} else {
return "false"; // This is a string and not a boolean true/false
}
}
echo is_str2_at_end_of_str1("Python", "thon") . "
";
echo is_str2_at_end_of_str1("JavaScript", "ript") . "
";