Skip to content

Instantly share code, notes, and snippets.

@dajve
Last active February 11, 2018 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dajve/a9fb14d815e14e5a4b79d6f26ae530a3 to your computer and use it in GitHub Desktop.
Save dajve/a9fb14d815e14e5a4b79d6f26ae530a3 to your computer and use it in GitHub Desktop.
<?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