2017-11-19 9 views
-4
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")."\n"; 
echo str2_in_str1("JavaScript","ript")."\n"; 

誰かがこの機能で何が起こったのか説明できますか?おかげさまで この関数についてのコードを私に教えてください。

+0

それはちょうど戻っている '真サブストリングがメインの 'string'に存在するか否かに基づいて' false'を返します。あなたの関数名は自明ですが、混乱は何ですか? –

答えて

-1

$str2$str1の末尾にあることを確認します。また、この比較のためにtrueまたはfalseを返します。

+0

道案内が下がっていますが、これは短くて正しい答えです、なぜ私は長い答えのような身体と答えの質に注意を払わないのだろうと思っています。私がこの質問に答える前に、彼らが削除した2つの間違った答えがありました。私の後で、新しい答えが追加され、変数名の変更のようないくつかの変更が加えられました。私はスタックオーバーフローで新しいし、誰かの態度が私を怒らせ、私はこの種の人々に何が間違っているのか分からない。 – Aqil

1

これはもっときれいにすることができます...あなたの変数に説明的な名前を付け、いくつかのコメントを追加することを学ぶときは、良いアイデアです。

私はここでこれをやって、より明確になっていることを期待しています。

は、だから私は...

NOTEをより消化のセクションにこれを分解して、それをコメントしている。これと同じ機能を実行するためのより良い方法があります...

/** 
* 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") . "\n"; 
echo is_str2_at_end_of_str1("JavaScript", "ript") . "\n"; 
関連する問題