views:

314

answers:

5

Is there any PHP function that encodes a string to a int value, which later I can decode it back to a string without any key?

+2  A: 

And int has 4 or 8 bytes depending on the platform, and each character in a string is one byte (or more depending on encoding). So, you can only encode very small strings to integers, which basically makes the answer to your question: no.

What do you want to accomplish?

Bart van Heukelom
+1  A: 

I would suspect not, since there are far more possible string combinations than integers within the MAX_INT.

Does it have to be an integer?

slifty
not really. numbers and lowercase letters are fine. I just want the encoded string to be as short as possible.
Alex
+1  A: 

i'm convinced that what you think you want to do is not really what you want to do. :-) this just sounds like a silly idea. As another user has asked before:) what do you need this for? What are your intentions?

Well now that you mentioned that numbers and a-z letter are acceptable, then I have one suggestion, you could loop through the individual letters' ordinal value and display that as a two-digit hexadecimal. You can then convert these hexadecimals back to the ordinal values of the individual characters. Don't know what kind of characters are you about to encode, possibly you will need to use 4-characters per letter (e.g. String Peter would become 00700065007400650072 ) Well... have fun with that, I still don't really see the rationale for doing what you're doing.

Peter Perháč
i have strings with various characters, and i want to encode it something that contains only numbers (and maybe a-z letters). the encoded string would be used as a html id tag on a element
Alex
edited my answer to reflect that a-z letters could be included
Peter Perháč
+1  A: 

Sure, you can convert strings to numbers and vice versa. Consider:

$a = "" + 1
gettype($a) // integer
$b = "$a"
gettype($b) // string

You can also do type casting with settype().

If I misunderstood you and you want to encode arbitrary strings, consider using base64_encode() and bas64_decode(). If you want to convert the base 64 string representation to a base 10 integer, simply use base_convert().

pr1001
A: 

Can you please help me to decode this....

Arjun