2

有人对此有 PHP 解决方案吗?

目标是有一个函数来接受这些

你好世界你好世界你好IBM

并返回这些

你好世界你好世界你好IBM

分别。

4

2 回答 2

3

来自苏格兰的麦克唐纳先生更喜欢他的名字大写,而来自爱尔兰的麦克唐纳先生更喜欢这样。在事先不知道您指的是哪位先生的情况下,很难知道哪个是“正确的”,这需要更多的上下文,而不仅仅是文件中的单词。

此外,英国广播公司(或者是英国广播公司?)已经开始拼写一些名字,比如 Nasa 和 Nato。它让我感到震惊;我非常不喜欢它。但这就是他们现在所做的。什么时候acrynom(或某些人更喜欢称之为“初始主义”)成为一个独立的词?

于 2012-05-28T00:36:33.180 回答
2

虽然这有点 hack,但您可以存储要保留大写字母的首字母缩略词列表,然后将字符串中的单词与$exceptions. 虽然 Jonathan 是正确的,但如果它的名称是您使用的而不是首字母缩略词,那么这个解决方案是无用的。但显然,如果来自苏格兰的麦克唐纳先生是正确的,那么它就不会改变。

See it in action

<?php
$exceptions = array("to", "a", "the", "of", "by", "and","on","those","with",
                    "NASA","FBI","BBC","IBM","TV");

$string = "While McBeth and Mr MacDonald from Scotland
was using her IBM computer to watch a ripped tv show from the BBC,
she was being watched by the FBI, Those little rascals were
using a NASA satellite to spy on her.";

echo titleCase($string, $exceptions);
/*
While McBeth and Mr MacDonald from Scotland
was using her IBM computer to watch a ripped TV show from the BBC,
she was being watched by the FBI, Those little rascals were
using a NASA satellite to spy on her.
*/

/*Your case example
  Hello World Hello World Hello IBM, BBC and NASA.
*/
echo titleCase('HELLO WORLD hello world Hello IBM, BBC and NASA.', $exceptions,true);


function titleCase($string, $exceptions = array(), $ucfirst=false) {
    $words = explode(' ', $string);
    $newwords = array();
    $i=0;
    foreach ($words as $word){
        // trim white space or newlines from string
        $word=trim($word);
        // trim ending coomer if any
        if (in_array(strtoupper(trim($word,',.')), $exceptions)){
            // check exceptions list for any words that should be in upper case
            $word = strtoupper($word);
        } else{
            // convert to uppercase if $ucfirst = true
            if($ucfirst==true){
                // check exceptions list for should not be upper case
                if(!in_array(trim($word,','), $exceptions)){
                    $word = strtolower($word);
                    $word = ucfirst($word);
                }
            }
        }
        // upper case the first word in the string
        if($i==0){$word = ucfirst($word);}
        array_push($newwords, $word);
        $i++;
    }
    $string = join(' ', $newwords);
return $string;
}
?>
于 2012-05-28T01:30:39.940 回答