homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Letters to numbers?

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

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




 9:07 pm on Jan 5, 2005 (gmt 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)

all lower already

Anyone for PHP Golf?


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

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

function letters2numbers($s)
if ((96 < ord($s[$i])) && (ord($s[$i]) < 123))
$r .= ++$c;
$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)

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!]



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

excellent thank you both

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved