PHP: Very simple Encode/Decode string

柔情痞子 提交于 2019-12-12 16:27:18

问题


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?


回答1:


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().




回答2:


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?




回答3:


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?




回答4:


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.




回答5:


op 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




回答6:


There is no function for PHP but I recently wrote a class to encrypt and decrypt a string in PHP. You can look at it at: https://github.com/Lars-/PHP-Security-class



来源:https://stackoverflow.com/questions/3145633/php-very-simple-encode-decode-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!