Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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 !

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top