Rasmus Rosengren Rasmus Rosengren - 4 months ago 7
PHP Question

How to output variance in very similar strings into an array?

I have something like this array of strings, as seen they are very similar, with the exception of the same one place in the string:

$strings = [
'This is +1% better than last time!',
'This is +2% better than last time!',
'This is +3% better than last time!',
'This is +4% better than last time!',
'This is +5% better than last time!',
...
];

// Psuedo code


From this I'd like to end up with

$array = [
'1',
'2',
'3',
'4',
'5',
...
];
// And preferrably
$string = 'This is +%s% better than last time!';


Via a function that takes any array of similar strings and outputs what is actually different in them.

Answer
function myfunc($strings) {
  // if the array is empty we don't have anything to do
  if (count($strings) == 0) return ""; 

  // count how many words are in a string (use the first one)
  $num_tokens = 0;
  $tok = strtok($strings[0], " ");
  while ($tok !== false) {
    $num_tokens++;
    $tok = strtok(" ");
  }

  $output = ""; 
  $tokens = []; 

  // iterate over each word of the string
  for ($w = 0; $w < $num_tokens; $w++) {
    // iterate over each string
    for ($s = 0; $s < count($strings); $s++) {
        // extract the same word of each string
        $tokens[$s] = strtok($strings[$s], " ");
        // remove that word from the string so it
        // will not be extracted again
        $strings[$s] = trim(substr($strings[$s], strlen($tokens[$s])));
    }   

    $first_token = true;
    $tmp = ""; 

    // If all words we have extracted are equal, we add that
    // word to the $output string. Otherwise we add '+%s%'.
    for ($s = 0; $s < count($strings); $s++) {
      // In the first iteration we just extract the word. We
      // will start comparing from the next iteration.
      if ($first_token) {
        $tmp = $tokens[$s];
        $first_token = false;
      } else {
        // If the words are not the same, we will add '+%s%' and
        // exit the loop.
        if ($tokens[$s] != $tmp) {
          $tmp = "+%s%";
          break;
        }   
      }   
    }   

    // Add the word to the $output string. If it's the first
    // word we don't add a white space before it.
    if ($output == "") {
      $output .= $tmp;
    } else {
      $output .= " $tmp";
    }   
  }

  return $output;
}

Example of usage:

$strings = [
        'This is +1% better than last time!',
        'This is +2% better than last time!',
        'This is +3% better than last time!',
        'This is +4% better than last time!',
        'This is +5% better than last time!',
];

echo myfunc($strings);