May 13, 2015

php function to get first letter of each word and make a unique key

php function to get first letter of each word and make a unique key

A PHP function will will help in those cases where we have to handle unexpected strings and we don’t know that how many elements can be in an array. Also if we are avoiding to save this array as a unique record in database too so this function can be helpful when you are thinking to rearrange such array but still string should be locatable with a unique key.


function get_unique_key($str){
$ret = '';
$str = htmlentities(trim($str));
if(trim($str)!=''){
$unique_arr = array();
$arr = explode(' ',$str);
$arr = array_filter($arr, 'strlen');
if(!empty($arr)){
foreach($arr as $word){
$unique_arr[] = preg_replace('/[^A-Za-z0-9\-]/', '', strtolower(substr(trim($word), 0, 1)));
}
$unique_arr = array_filter($unique_arr, 'strlen');
$ret = implode('', $unique_arr);
}
}
return $ret;
}

Last updated: May 14, 2015