The personal ramblings of an early participant in meaningless online rambling. Family (especially children), PHP, Linux, and occasionally PS3 games are discussed.

a function for breaking two strings by their overlapping / run-in parts


<?php /**
 * split two strings based on their overlapping portion. The expectation
 * is that string 1 ends with something that can also be found in string 2.
 * Returns an array with indexes 0, 1, and 2 indicating the pre-overlap(0),
 * overlap(1), and post-overlap(2) portions of the two strings
 *
 * @example splitByOverlap("ABCD", "CDEF") // array("AB", "CD", "EF")
 * @param string $str1
 * @param string $str2
 * @return array (0) str1 before overlapping segment, (1) overlap, (2) str2 after the overlapping segment
 */
function splitByOverlap($str1, $str2) {
  $matches = array();
  $results = preg_match('/(.*?)(.+)•\2(.*)/', $str1.'•'.$str2, $matches);

  if ($results) {
    unset($matches[0]);
    return array_merge($matches);
  }
  return false;
}

0 comments: