Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Function to correct the issue of having duplicate variables in the same string
<?php
/*
* Function to correct the issue of having duplicate variables in the same string
*
* Example usage:
* $listWords['baggage_loss_amount'] = sanitizeDuplicates($listWords['baggage_loss_amount'], 'AMOUNT&&', array('3.000', '350', '700'));
* $listWords['health_search_amount'] = sanitizeDuplicates($listWords['health_search_amount'], 'AMOUNT&&', array('2.000', '15.000'));
*
* @param string $string (current string to filter)
* @param string $duplicatedVar (duplicated variable name without closures: '<' and '>')
* @param array $replace (values replacement array for the different variables)
* @return filtered string with correct values replacement for each given duplicated variable
*/
public static function sanitizeDuplicates($string, $duplicatedVar, $replace) {
// replace the variable names with the same name without the '<' and the '>' to avoid parsing them
$string = str_replace('<'. $duplicatedVar .'>', $duplicatedVar, $string);
// create and empty array to push the string words in the loop below
$finalArray = array();
// add spaces when those are missing from the original variables (i.e.: link tags)
if ( substr_count($string, '&& ') != substr_count($string, '&&') ) {
$string = str_replace($duplicatedVar, ' ' . $duplicatedVar . ' ', $string);
}
// counter initialization to number same variables and make them to diferentiate from each other
$c = 0;
// main words array
$arr = preg_split('/\s+/', $string);
// Sorting/numbering duplicated variables: split the string by each word and walk the pre_split created array
foreach ($arr as $key => $word) {
// once found our variable ...
if ($word == $duplicatedVar) {
foreach ($replace as $key2 => $value) {
// ... and sort out the current corresponding value ...
$key2 = $c;
// ... replace it with the corresponding value and push it into the new associative array
$finalArray[$key] = $replace[$key2];
// we need only the first result for each
break;
}
$c++;
} else {
// the rest of the string words are simply pushed into the new associative array
$finalArray[$key] = $word;
}
}
// re-construct the sentence with correct variables associations
$result = $finalArray = implode(" ", $finalArray);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment