w3resource

PHP String Exercises: Find the first character that is different between two strings


11. Find First Character Difference Between Strings

Write a PHP script to find the first character that is different between two strings.

String1 : 'football'
String2 : 'footboll'

Visual Presentation:

PHP String Exercises: Find the first character that is different between two strings

Sample Solution:

PHP Code:

<?php
// Define two strings to compare
$str1 = 'football';
$str2 = 'footboll';

// Calculate the position of the first difference between the two strings
$str_pos = strspn($str1 ^ $str2, "\0");

// Output the position of the first difference along with the characters at that position
printf('First difference between two strings at position %d: "%s" vs "%s"',
    $str_pos, $str1[$str_pos], $str2[$str_pos]);
printf("\n");
?>

Output:

First difference between two strings at position 5: "a" vs "o"

Explanation:

In the exercise above,

  • String comparison:
    • Two strings are defined: $str1 with the value 'football' and $str2 with the value 'footboll'.
  • First difference calculation:
    • The strspn() function calculates the position of the first difference between the two strings.
    • The bitwise XOR operator () compares each character of the strings.
    • The strspn() function returns the length of the initial segment of $str1 ^ $str2 consisting of characters not present in the mask. This is "\0" (the null character).
  • Output:
    • The position of the first difference is printed along with the characters at that position in both strings.

Flowchart :

Flowchart: Find the first character that is different between two strings

For more Practice: Solve these Related Problems:

  • Write a PHP function to compare two strings character by character and output the position and differing characters when a mismatch is found.
  • Write a PHP script that identifies and returns the index of the first non-matching character between two strings, handling different lengths.
  • Write a PHP program to output a formatted message indicating the first position where two strings differ, using loop-based comparison.
  • Write a PHP script to compare two strings and if they differ, print both differing characters along with their ASCII values.

Go to:


PREV : Replace First Occurrence of "the".
NEXT : Convert String to Array (Split by New Line).

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.