PHP将大写单词转换为小写,但将ucfirst保留为小写单词

时间:2018-01-17 13:28:07

标签: php string

示例:

THIS IS A Sentence that should be TAKEN Care of

输出应为:

This is a Sentence that should be taken Care of

规则

  • 将大写字词转换为小写
  • 保持小写单词的大写第一个字符保持不变
  • 将句子中的第一个字符设置为大写。

代码

$string = ucfirst(strtolower($string));

失败

它失败了,因为没有保留第一个字。

This is a sentence that should be taken care of

4 个答案:

答案 0 :(得分:2)

您可以针对这些规则测试每个单词:

$str = 'THIS IS A Sentence that should be TAKEN Care of';
$words = explode(' ', $str);
foreach($words as $k => $word){
    if(strtoupper($word) === $word || // first rule
           ucfirst($word) !== $word){ // second rule 
        $words[$k] = strtolower($word);
    }
}
$sentence = ucfirst(implode(' ', $words)); // third rule

输出:

  

这是一个应该照顾的句子

一点解释:
由于您有重叠的规则,您需要单独比较它们,所以......

  • 将句子分解为单独的单词,并根据规则检查每个单词;
  • 如果单词是UPPERCASE,请将其变为小写; (THIS,IS,A,TAKEN)
  • 如果这个词是第一个,那就别管它了; (句子,关怀)
  • 如果单词不是ucfirst,请将其变为小写,(即,应该,是)

答案 1 :(得分:2)

您可以将句子分解为单个单词,然后对每个单词应用格式化功能:

$sentence = 'THIS IS A Sentence that should be TAKEN Care of';

$words = array_map(function ($word) {
    // If the word only has its first letter capitalised, leave it alone
    if ($word === ucfirst(strtolower($word)) && $word != strtoupper($word)) {
        return $word;
    }

    // Otherwise set to all lower case
    return strtolower($word);
}, explode(' ', $sentence));

// Re-combine the sentence, and capitalise the first character
echo ucfirst(implode(' ', $words));

请参阅https://eval.in/936462

答案 2 :(得分:1)

   System.setProperty("webdriver.gecko.driver", "//eclipse-     Oxygen/aaa/src/test/java/aa/aaa/geckodriver 4");


 System.setProperty("webdriver.firefox.bin","/Applications/Firefox.app/Contents/MacOS/firefox-bin");
    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability("acceptInsecureCerts", true);
    capabilities.setJavascriptEnabled(true);

    driver = new FirefoxDriver(capabilities);
    driver.get("https://www.google.com");

<强>输出:

这是一个应该照顾的句子

答案 3 :(得分:-2)

$ string =&#39;这是一句应该采取的句子&#39 ;; $ arr = explode(&#34;&#34;,$ string);

foreach($arr as $v)
    {
        $v=ucfirst(strtolower($v));
        $stry=$stry.' '.$v;
    }

echo $ stry;