Welcome to WebmasterWorld Guest from 54.196.243.192

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Letters to numbers?

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

Junior Member

10+ Year Member

joined:Nov 29, 2003
posts:94
votes: 0


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)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 3, 2003
posts:1633
votes: 0


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)

Junior Member

10+ Year Member

joined:Nov 29, 2003
posts:94
votes: 0


all lower already

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 3, 2003
posts:1633
votes: 0


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)

Junior Member

10+ Year Member

joined:June 3, 2002
posts:169
votes: 0


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)

Junior Member

10+ Year Member

joined:Nov 29, 2003
posts:94
votes: 0


excellent thank you both