Write a PHP program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string

  • برمجة بي اتش بي

Write a PHP program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string. Do not count the end substring

الأجوبة

<?php
function test($s)
{
    $last_two_char = substr($s, strlen($s)-2, 2);
    $ctr = 0;

    for ($i = 0; $i < strlen($s)-2; $i++)
        {
           if (substr($s, $i, 2) == $last_two_char) 
           $ctr = $ctr +1;
        }
    return $ctr;
 }

echo test("abcdsab")."\n";
echo test("abcdabab")."\n";
echo test("abcabdabab")."\n";
echo test("abcabd")."\n";

Sample Output:

1
2
3
0
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...