views:

57

answers:

4

The first method that springs to mind is reading each character and converting it to its ASCII value. Are there any other methods of doing this? I would like to be able to give a php script a string, and have it turn that same string (that may or may not contain numbers or symbols) into the same series of numbers every time.

A: 

Maybe you want to read about type casting and juggling?

Umang
I already read that page. It's not what I'm looking for. For example, I want to give PHP the value "clock" and have it turn that into a number like "83653" every time it gets that value.
VGambit
Ah, understand your question now. Yes, the accepted answer seems to be the right way to go.
Umang
A: 

Can you provide some bounds for this function? Would it need to do fractions or decimals? Or numbers less than zero? How high would it need to go? English only?

Jules
It needs to be a whole number greater than zero. The only characters it would need to convert are characters that can be typed in from a single keystroke.
VGambit
Oh, I thought you wanted to convert "one" to 1, "two" to 2 and so on. Yeah, you want hashing (as someone else here has said). Hashing will give you a huge number though, that might not be what you want.
Jules
+1  A: 

This would work (but I'm not sure if I have fully grasped what you want to do):

function string2num($in_str) {
    $out_str = '';
    $chars = unpack('c*', $in_str);

    foreach($chars as $char) {
        $out_str .= $char;
    }

    return $out_str;
}

// Outputs:
// 8410410511532105115329732115116114105110103

$num = string2num('This is a string');
print "$num\n";
Mike
It came down to either this method or md5 hashing, but I decided to go with the hash, since it always has a specific length (32 characters). I hadn't thought of hashing before, as I usually associate that with files rather than text strings (although when you get down to it, that's all a file really is). I initially wanted it to just be numbers, but I don't think it really matters too much.
VGambit
I think that's a good choice.
Mike
+2  A: 

So, you're talking of hashing.
MD5() or (or sha1() as some local paranoids insists) can give you that number. Though a hexdecimal one. I hope it will fit your unclear goals.

Col. Shrapnel
I agree - it does sound like a hash value is required. If necessary, the raw_output flag could be added to the MD5 or SHAx function to give binary output instead of hex.
Mike