Welcome to WebmasterWorld Guest from 184.73.126.70

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Letters to numbers?

   
8:55 pm on Jan 5, 2005 (gmt 0)

10+ Year Member



Hi,
anyone know of an easy way to convert letters to numbers with PHP rather that str_replace "a","1" and so on?

i need to convert say bsg55vd7 to say 12355127 but not random it needs to convert the same everytime.

basicly i need to remove letters but not shorten the string

Thanks

9:07 pm on Jan 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do you want upper case and lower case handled the same, e.g A=1 and a=1?

Anyone for PHP Golf?

9:18 pm on Jan 5, 2005 (gmt 0)

10+ Year Member



all lower already

Anyone for PHP Golf?
9:32 pm on Jan 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's a starter for 10 - probably a way more efficient way to do it though...


function letters2numbers($s)
{
for($i=0;$i<strlen($s);$i++)
{
if ((96 < ord($s[$i])) && (ord($s[$i]) < 123))
{
$r .= ++$c;
}
else
{
$r .= $s[$i];
$c = 0;
}
}
return $r;
}

- note that this will increase the length of the string if you ever have a sequence of more than 9 characters. Your only alternative would be to wrap back to 0.

9:35 pm on Jan 5, 2005 (gmt 0)

10+ Year Member



I had to do something similar at one point and here is the function I used (had to remove a few things, so it might not work, but should be a good start):

function convertLettersToNumbers($myString) {

for ($i = 0; $i < strlen($myString); $i++) {
$asciiValue = ord($myString{$i});

if ($asciiValue > 96 && $asciiValue < 123) {
$myString{$i} = $asciiValue - 96;
}
}

return $myString;
}

You might have to change a few things if your conversion isn't linear (a=1, b=2, etc.)

Hope that helps

[added: doh! I'm typing too slow!]

mavherick

10:20 pm on Jan 5, 2005 (gmt 0)

10+ Year Member



excellent thank you both
 

Featured Threads

Hot Threads This Week

Hot Threads This Month