You can use a Huffman encoding scheme.
Here is an example I wrote a while back:
http://www.brettsbsd.net/~estrabd/SCHOOL/CS638/huffman.php
You'll have to modify it because it because it just returns a the 1's and 0's as a string. It also doesn't handle 1's and 0's when decoding a string that originally contained 1's and 0's...I intend on fixing these issues when I have time, but it does *most* of what you might want...