正确的案例,不会破坏像IBM,NASA等

时间:2012-05-28 00:25:09

标签: php regex string upcase

有没有人有这方面的PHP解决方案?

目标是拥有一个采用这些

的功能

你好世界 你好,世界 你好IBM

并返回这些

Hello World 你好,世界 你好IBM

分别

2 个答案:

答案 0 :(得分:3)

来自苏格兰的麦克唐纳先生更喜欢这个名字,而爱尔兰的麦克唐纳先生更喜欢这样。如果事先不知道你指的是哪个绅士,就很难知道哪个是“正确的”,这需要更多的背景而不仅仅是文件中的文字。

此外,英国广播公司(或英国广播公司?)已经采取拼写一些名称,如美国国家航空航天局和北约。它刺激我;我非常不喜欢它。但这就是他们这些天所做的事情。什么时候丙烯酸(或某些人更喜欢称之为“初始主义”)本身就成了一个词?

答案 1 :(得分:2)

这是一个黑客攻击,您可以存储要保持大写的首字母缩略词列表,然后将字符串中的单词与$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;
}
?>