w3resource

PHP Exercises: Compare two given strings and return the number of the positions where they contain the same length 2 substring

PHP Basic Algorithm: Exercise-35 with Solution

Write a PHP program to compare two given strings and return the number of the positions where they contain the same length 2 substring.

Sample Solution:

PHP Code :

<?php
// Define a function that counts the number of common two-character substrings between two strings
function test($s1, $s2)
{
    // Initialize a counter variable
    $ctr = 0;

    // Iterate through substrings of the first string
    for ($i = 0; $i < strlen($s1)-1; $i++)
    {
        // Extract a two-character substring from the first string
        $firstString = substr($s1, $i, 2);

        // Iterate through substrings of the second string
        for ($j = 0; $j < strlen($s2)-1; $j++)
        {
            // Extract a two-character substring from the second string
            $secondString = substr($s2, $j, 2);

            // Check if the two substrings are equal, and increment the counter if they are
            if ($firstString == $secondString) 
                $ctr++;
        }
    }

    // Return the final count of common two-character substrings
    return $ctr;
}

// Test the function with different pairs of strings
echo (test("abcdefgh", "abijsklm"))."\n";
echo (test("abcde", "osuefrcd"))."\n";
echo (test("pqrstuvwx", "pqkdiewx"))."\n";
?>

Sample Output:

1
1
2

Flowchart:

Flowchart: Check whether the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check whether the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.
Next: Write a PHP program to create a new string of the characters at indexes 0,1,4,5,8,9 ... from a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.