php代码
<?php /** * 字符串,重复值压缩 * @param string $str 字符串 * @param string $code_type encode|decode * @return string|mixed */ function str_compress($str, $code_type='encode') { $code_type = strtolower(trim($code_type)); if ('encode' == $code_type || $code_type) { $res = preg_replace_callback('#(.)(\1+)#is', function($match){ return $match [1] . '[' . strlen($match[0]) . ']'; }, $str); } else { $res = preg_replace_callback('#(.)\[(\d+)\]#is', function($match){ return str_repeat($match [1], $match [2]); }, $str); } return $res; } // 测试 ----------------- $old_str = $str = 'aavaabbcce'; echo $old_str; echo ""; $str = str_compress($str); echo $str; echo ""; $str = str_compress($str, 0); echo $str; echo ""; if ($str == $old_str) { echo 1; } else { echo 0; }