Reputation: 65
I have a string with single letter codes like
MGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREA
I would like to print a serial number over each letter in the string.
like
123456789101112131415161718192021222324252627282930
MGCLGNSKTED Q R N E E K A Q R E A M G C L G N S K T
thanks in advance.
Upvotes: 1
Views: 433
Reputation: 146490
A nice excuse to learn about some fancy PHP functions:
<?php
$single_letter_codes = 'MGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREA';
foreach(range(1, strlen($single_letter_codes)) as $number){
echo $number;
}
echo PHP_EOL;
foreach(str_split($single_letter_codes) as $index => $letter){
// Changed ' ' to '·' to make it visible
echo str_pad($letter, strlen($index+1), '·', STR_PAD_LEFT);
}
echo PHP_EOL;
Assumptions:
Right align, as in:
10
A
And we get:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
MGCLGNSKT·E·D·Q·R·N·E·E·K·A·Q·R·E·A·M·G·C·L·G·N·S·K·T·E·D·Q·R·N·E·E·K·A·Q·R·E·A·M·G·C·L·G·N·S·K·T·E·D·Q·R·N·E·E·K·A·Q·R·E·A
Update: In order to display this as HTML, you need to enforce a fixed width font. The simplest way is to enclose everything into a <pre></pre>
tag set.
I'll leave as an exercise for the reader how to use spaces instead of dots.
Upvotes: 2
Reputation: 1803
Perhaps this can help...
<?php
$str = 'MGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREAMGCLGNSKTEDQRNEEKAQREA';
$len = strlen($str);
$nums = '';
$lets = '';
for ($i = 1; $i <= $len; $i++) {
$nums .= $i;
$lets .= sprintf('% ' . strlen($i) . 's', $str[$i - 1]);
}
echo $nums . "\n" . $lets;
You will get
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
MGCLGNSKT E D Q R N E E K A Q R E A M G C L G N S K T E D Q R N E E K A Q R E A M G C L G N S K T E D Q R N E E K A Q R E A
Upvotes: 0
Reputation: 1962
If I got you right, then this is what you need (caution, there might be small mistakes, test):
function printSerial($string){
$map = array(
'M' => 1,
'G' => 2,
'C' => 3,
// ... please continue
);
$output = '';
for($i=0; $i<strlen($string); $i++){
$output .= $map[$string[$i]];
}
echo $output;
}
Upvotes: 0