/** * * 过滤包含,当前关键词在后面出现,后面删掉 * 关键字 留短不留长 * @param $arr=array(); * @return $newArr=array(); * @update 2013/9/24 */ function arrFilter(& $arr ){ $newArr =& $arr ; $count = count ( $newArr ); for ( $i =0; $i < $count ; $i ++){ for ( $k = $count -1; $k > $i ; $k --){ $needle = $newArr [ $i ]; $haystack = $newArr [ $k ]; if (! $needle ) continue ; $rst = substr ( $haystack ,0, strlen ( $needle ))== $needle ?1:0; if ( $rst ){ array_splice ( $newArr , $k ,1); array_values ( $newArr ); $count --; }; } } } //优化后算法 function arrFilter2(& $arr ){ sort( $arr ); foreach ( $arr as $v1 ) { while ( $v2 = current( $arr )){ $l1 = strlen ( $v1 ); $l2 = strlen ( $v2 ); if ( $l1 > $l2 or $v1 != substr ( $v2 ,0, $l1 ) ) break ; $k = key( $arr ); unset( $arr [ $k ]); } } } |
//字符串有短到长排列 function cmpStr( $str1 , $str2 ){ $a = strlen ( $str1 ); $b = strlen ( $str2 ); if ( $a == $b ) { if ( $str1 == $str2 ){ return 0; } else { return ( $str1 < $str2 ) ? -1 : 1; } //return 0; } return ( $a < $b ) ? -1 : 1; } $aS = array ( 'baaab' , 'aa' , 'cc' , 'bb' , 'aaaa' , 'dd' , 'aaaaa' ); usort( $aS , "cmpStr" ); |