0

Let's say I have a string like this:

whateverthisis123 #_-

I want to convert this string into a number within a number interval forexample within 1-1000.

The above string could for example be converted into

387

This comes with a few rules:

  • The string could contain every character.
  • The number should feel random but cannot be. The same string should always return the same number.
  • Longer string should not make the number higher. Should feel random.
  • aaa should not give a number like 222. Should feel random.
  • It should accept the interval for example 1 up to 1000.
  • "thisstring" and "thisstring1" are alike. The numbers should still not be alike.

Is there a built in function for this in PHP? If not, any clever idea how to create something like this?

Maybe it's easier if first converting in to MD5? http://www.php.net/manual/en/function.md5.php

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

2 Answers2

2

You're essentially describing a hash function. MD5 looks like the way to go. If you need to convert it to a number you could intval() it. To keep it between 1-1000, use $number % 1000.

Note: If this has to do with security/passwords, it's a bad idea.

Jeff
  • 789
  • 4
  • 13
  • 4
    @OP If you're using this as a method of security in any aspect, please consider using [bcrpyt](http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php) as opposed to MD5. MD5's lack of uniqueness makes it vulnerable to multiple attacks. – Ohgodwhy Apr 04 '14 at 06:42
  • No, I'm not going to use it for security. I might have a URL to a quote and on that URL I want a "random" avatar image. This function will create a link to for example 387.jpg for that URL. – Jens Törnell Apr 04 '14 at 07:37
  • 1
    Sounds like a perfect use case then. Just wanted to make sure! – Jeff Apr 04 '14 at 07:39
  • I tested it and almost always I get 0 in result. It seems like the intval returns 0 in many cases. – Jens Törnell Apr 04 '14 at 10:17
1

Extended from my comment, here is a full code example (more fun way than just hash..)

 <?php
  function numberout(string $input)
      {
         $hash=md5($input);
         $calculate=hexdec(substr($hash,0,3)); //take out 3 digits
         $maxhex=4095; //3 digit hex ,65535 for 4 digit hex and so on...
         $out = ($calculate*1000)/$maxhex;
         return round($out);
      }
 ?>

Sorry if this is programmartically wrong, I was used to c# and I haven't test this yet. So if there is any error I hope someone to edit it

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
Poomrokc The 3years
  • 1,099
  • 2
  • 10
  • 23