English 中文(简体)
我如何计算一下“字母号码”的总和?
原标题:How can I calculate the sum of "letter numbers" in a string?
  • 时间:2012-01-13 10:56:38
  •  标签:
  • php
  • counter

是否有任何现成的购买力平价功能,通过这种功能,我可以计算字母缩略语中字母的指数。

<?php
$a = "testword";
echo "Count of Characters is: " . strlen($a); 
?>

我现在想得到这个词的累积“总数”。

e.g.

  • A is the first letter of the alphabet so it maps to 1
  • B is the second letter of the alphabet so it maps to 2
  • C is the third letter of the alphabet so it maps to 3
  • D is the fourth letter of the alphabet so it maps to 4

因此,ABCD的字句 1+2+3+4=10

同样,我需要的是“前言”或任何字。

最佳回答
function WordSum($word)
{
    $cnt = 0;
    $word = strtoupper(trim($word));
    $len = strlen($word);

    for($i = 0; $i < $len; $i++)
    {
        $cnt += ord($word[$i]) - 64; 
    }

    return $cnt;
}

var_dump(WordSum("testword"));
问题回答

仅表明一种完全不同的方法,因为她很乐意展示一些PHP阵列功能:

$data = "testword";

$testResult = array_values(array_merge(array_fill_keys(range( A , Z ),
                                                       0
                                                      ),
                                       array_count_values(str_split(strtoupper($data)
                                                                   )
                                                         )
                                      )
                          );
$wordCount = 0;
foreach($testResult as $letterValue => $letterCount) {
    $wordCount += ++$letterValue * $letterCount;
}

var_dump($wordCount);




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签