I'm trying to create a 6 digit number from a string of letters before a # sign.

For instance I'd like to take "seaweed#" and take the 6 last letters before the "#" sign and convert them to numbers based on each letters position in the alphabet assuming a=1, b=2, c=3 etc.

I've been looking through PHP's manual of string functions but logic is failing me this morning. Most likely because I haven't had my coffee yet. Some help would be appreciated.

Try the following:

$string='seaweed#';
$strb=explode('#',$string);
$strb[0]=str_replace(array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26'),$strb[0]);
$newstring=$strb[0].'#'.$strb[1];
echo $newstring;

Try the following:

$string='seaweed#';
$strb=explode('#',$string);
$strb[0]=str_replace(array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'), array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26'), $strb[0]);
$newstring=$strb[0].'#'.$strb[1];
echo $newstring;

Thanks cwarn. I modified your code to fit my needs.

<?php
$string='seaweed#';
$strb=explode('#',$string);
//Check if the length of the string before # is more than 3 letters
if(strlen($strb[0])<3)
{
	//if it isn't then add in random numbers to meet the 6 digit requirement
        $length = 3 - strlen($strb[0]);
	for($i=1; $i<=$length; $i++)
	{
		$strb[0] = $strb[0].rand(10,99);
	}
	$replace = $strb[0];
}
else
{
        //the length of the string is more than 3 letters so select the last 3 letters before the #
	$replace = substr($strb[0], -3);
}
$digits = str_replace(array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'), array('01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26'), $replace);

//Uncomment the lines of code below in order to check that everything is working
//$newstring = $strb[0].'#'.$digits;
//echo $newstring."\n";

//echo the result
echo $digits;
?>

EDIT: In the code I look for the last three letters. The reason for this is that the corresponding numbers have 2 digits each.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.