Skip to content

Instantly share code, notes, and snippets.

@rotten77
Last active August 29, 2015 14:04
Show Gist options
  • Save rotten77/6e7b41ba76d3025a8034 to your computer and use it in GitHub Desktop.
Save rotten77/6e7b41ba76d3025a8034 to your computer and use it in GitHub Desktop.
Get repeating strings in PHP array
<?php
/**
* ===========================================
* Compare strings and return repeating string
* ===========================================
*
* EXAMPLE:
*
* $strings = array(
* "oh this is repeating string number one",
* "and this is repeating string too",
* "this is repeating string also",
*);
*
* echo getRepeatingString($strings); // "this is repeating string"
*
* @author Jan Zatloukal / rotten77.cz
* @param array $strings
* @return string $compare
*/
function getRepeatingString($strings) {
foreach($strings as $key=>$string) {
$strings[$key] = mb_strtolower($string, "utf-8");
}
foreach($strings as $key=>$string) {
$compareStartA = -1;
$compareStartB = -1;
$strA = ($key==0 ? explode(" ", $strings[0]) : $compare);
$compare = array();
$strB = explode(" ", $string);
foreach($strA as $keyA=>$valA) {
foreach($strB as $keyB=>$valB) {
if($valA==$valB) {
$compareStartA = ($compareStartA>=0 ? $compareStartA : $keyA);
$compareStartB = ($compareStartB>=0 ? $compareStartB : $keyB);
}
}
}
$idx=0;
foreach($strA as $keyA=>$valA) {
if($strA>=$compareStartA) {
if(isset($strB[$compareStartB+$idx]) && $valA==$strB[$compareStartB+$idx]) {
$compare[] = $valA;
$idx++;
}
}
}
}
return implode(" ", $compare);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment