当前位置:Gxlcms > PHP教程 > php简单压缩英文字符串的代码

php简单压缩英文字符串的代码

时间:2021-07-01 10:21:17 帮助过:15人阅读

  1. //replacement来自上个版本的加密替换

  2. function compress_func($match) {return strlen($match[0]).$match[0]{0};}
  3. function uncompress_func($match) {return str_repeat($match[2], $match[1]);}
  4. function compress($str) {
  5. $i = 0;
  6. $pattern = array();
  7. while(isset($replacement{$i})) array_push($pattern, "/".$replacement{$i++}."{2,}/");
  8. return preg_replace_callback($pattern, "compress_func", $str);
  9. }

  10. function uncompress($str) {

  11. return preg_replace_callback("/(d+)(w)/", "uncompress_func", $str);
  12. }
  13. ?>

下面再分享个awk实现字符串压缩的代码。 AWK,通用格式压缩字符串:

  1. #!/bin/awk
  2. function compress(str, _ARGVEND_, str_out, str_len, i, s, l) {
  3. str_out = "";
  4. str_len = length(str);
  5. s = "";
  6. l = 1;
  7. for(i =1; i <= str_len; i++) {
  8. if(substr(str, i, 1) == s) l++;
  9. else {
  10. if(s != "") {
  11. if(l > 1) str_out=str_out""l
  12. str_out=str_out""s;
  13. }
  14. s = substr(str, i, 1);
  15. l = 1;
  16. }
  17. }
  18. return str_out;
  19. }
  20. function uncompress(str, _ARGVEND_, str_out, str_len, i, c) {
  21. str_out = "";
  22. str_len = length(str);
  23. for(i =1; i <= str_len; i++) {
  24. c = 0;
  25. while(substr(str, i, 1)~/[0-9]/) {
  26. c = c*10+substr(str, i, 1);
  27. i++;
  28. }
  29. if(c < 1) c = 1;
  30. while(c--) str_out = str_out""substr(str, i, 1);
  31. }
  32. return str_out;
  33. }

人气教程排行