Last active
February 11, 2018 17:08
-
-
Save dajve/a9fb14d815e14e5a4b79d6f26ae530a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://www.facebook.com/groups/2204685680/permalink/10156550592900681/ | |
// These are your inputs | |
$str1 = "We all go to college"; | |
$str2 = "We all go to temple"; | |
// Create array of lowercase versions of the words | |
// Lowercase to allow our diff to not get caught up in case sensitivity | |
$ar1 = array_filter(array_map('trim', explode(' ', strtolower($str1)))); | |
$ar2 = array_filter(array_map('trim', explode(' ', strtolower($str2)))); | |
// Now we get an array of all the words which only appear in either of the arrays | |
$diff = array_merge( | |
array_diff($ar1, $ar2), | |
array_diff($ar2, $ar1) | |
); | |
// This is what we'll replace the differences with | |
$replacePattern = '<span class="highlight">${1}</span>'; | |
$str1_highlighted = $str1; | |
$str2_highlighted = $str2; | |
foreach ($diff as $part) { | |
$str1_highlighted = preg_replace( | |
sprintf('/(%s)/i', preg_quote($part)), | |
$replacePattern, | |
$str1_highlighted | |
); | |
$str2_highlighted = preg_replace( | |
sprintf('/(%s)/i', preg_quote($part)), | |
$replacePattern, | |
$str2_highlighted | |
); | |
} | |
// Now, $str1_highlighted and $str2_highlighted can be output as desired |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment