正确的案例,而不会破坏IBM,NASA等东西



>有人有PHP解决方案吗?

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

世界您好世界您好你好 IBM

并返回这些

世界您好世界您好你好 IBM

分别。

来自苏格兰的麦克唐纳先生更喜欢这样大写他的名字,而来自爱尔兰的麦克唐纳先生更喜欢这样。 如果不事先知道你指的是哪位先生,就很难知道哪个是"正确的",这需要比文件中的单词更多的上下文。

此外,BBC

(或者说是BBC?)已经开始拼写一些名字,如NASA和Nato。 它震撼了我;我非常不喜欢它。 但这就是他们现在所做的。 acrynom(或有些人喜欢称之为"首字母缩写")什么时候成为一个独立的词?

这有点黑客,您可以存储要保持大写的首字母缩略词列表,然后将字符串中的单词与$exceptions列表进行比较。虽然乔纳森是正确的,但如果它命名你的工作而不是首字母缩略词,那么这个解决方案是没有用的。但显然,如果来自苏格兰的麦克唐纳先生处于正确的情况,那么它就不会改变。

查看实际效果

<?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;
}
?>