欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2024-02-06 13:27:46
...
  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 if(substr(str, i, 1) == s) l++;
  8. else {
  9. if(s != "") {
  10. if(l > 1) str_out=str_out""l
  11. str_out=str_out""s;
  12. }
  13. s = substr(str, i, 1);
  14. l = 1;
  15. }
  16. }
  17. return str_out;
  18. }
  19. function uncompress(str, _ARGVEND_, str_out, str_len, i, c) {
  20. str_out = "";
  21. str_len = length(str);
  22. for(i =1; i c = 0;
  23. while(substr(str, i, 1)~/[0-9]/) {
  24. c = c*10+substr(str, i, 1);
  25. i++;
  26. }
  27. if(c while(c--) str_out = str_out""substr(str, i, 1);
  28. }
  29. return str_out;
  30. }
复制代码