Compressing a string, end result without line breaks?

1.8k views Asked by At

I'm trying to compress any given string to a shorter version, copy paste-able compressed string that doesn't contain any line breaks.

I tried gzcompress, but then copy/pasting the result into a different php script and trying to gzuncompress throws "Warning: gzuncompress(): data error"

Is there any native php function that compresses a string, and the result is a string without any line breaks?

Thanks.

3

There are 3 answers

5
Dan Breen On BEST ANSWER

You could try base64_encode / base64_decode. If you're compressing to binary for cut and paste, I would suggest you base64 encode it first.

3
Adrien Plisson On

you can escape your line-breaks after compressing: run gzcompress() on your string, replace line-breaks with a known 2 characters pair in the compressed result. to uncompress, replace the known 2 characters pair by line-breaks, then run gzuncompress()...

actually, you will need to perform 2 replacements. since i can't express this in english (not my native tongue), here is an example: use '+n' to escape line-breaks. you will first need to escape every '+' which are standing alone, since if it is followed by a 'n' it will be accidentally replaced by a line-break when uncompressing; let's chose '++' for escaping '+. then replace line-breaks by '+n'. when uncompressing, replace every '+n' pair by a line-break, then every '++' pair by '+'. that's it !

0
Tim On

It's impossible to design a general compression algorithm which always produces output shorter than the input. So, if you always want shorted output than input, you have to start restricting what your algorithm can do. You need to think about which characters are acceptable in the input (long) string, and which characters are acceptable in your output (short) string. Once you have a good idea of these, you can start working out what your options are.