2013-10-01 43 views
0

所以我必须制作一个网页,其中包含一个可以填写的文本区域(由空格分隔的单词)。仅在第一个字母不是大写的情况下才将字符串转换为小写字母

因此,必须在屏幕上显示文本中的每个单词(每行一个单词),其中大写字母的每个单词都被转换为小写字母,除非该单词在过程中的第一个字母是大写字母。

例子:'这是StackOverflow的网站'是“”这是#1网站”

我知道我有爆炸(),strotoupper()和strotolower(工作),我只是“T得到的代码工作

+0

'ucfirst(用strtolower($ your_text))'将让你关闭。但如果第一个字母不是大写,那么只需要大写,在做ucfirst/strtolower之前,您会想要爆炸并进行一些测试。 –

+0

这将使所有单词的第一个字母上移。 – TheWolf

+0

请与我们分享您迄今的代码;这样我们可以说出问题。 –

回答

1
$text = 'tHIs is the StacKOverFlOW SiTE'; 
$oldWords = explode(' ', $text); 
$newWords = array(); 

foreach ($oldWords as $word) { 
    if ($word[0] == strtoupper($word[0]) 
     $word = ucfirst(strtolower($word)); 
    else 
     $word = strtolower($word); 

    $newWords[] = $word; 
} 
2
function lower_tail($str) { 
    return $str[0].strtolower(substr($str, 1)); 
} 

$sentence = "tHIs is the StacKOverFlOW SiTE"; 
$new_sentence = implode(' ', array_map('lower_tail', explode(' ', $sentence))); 

更新:

这里是一个更好的版本,可处理一些其他情况:

$sentence = "Is tHIs, the StacKOverFlOW SiTE?\n(I doN'T know) [A.C.R.O.N.Y.M] 3AM"; 
$new_sentence = preg_replace_callback(
    "/(?<=\b\w)(['\w]+)/", 
    function($matches) { return strtolower($matches[1]); }, 
    $sentence); 
echo $new_sentence; 
// Is this, the Stackoverflow Site? 
// (I don't know) [A.C.R.O.N.Y.M] 3am 
// OUTPUT OF OLD VERSION: 
// Is this, the Stackoverflow Site? 
// (i don't know) [a.c.r.o.n.y.m] 3am 

(注:PHP 5.3+)

+0

谢谢你,这真的很有用,并教会了我的诀窍。 – user1833552

0

我会写这样

$tabtext=explode(' ',$yourtext); 
foreach($tabtext as $k=>$v) 
{ 
    $tabtext[$k]=substr($v,0,1).strtolower(substr($v,1)); 
} 
$yourtext=implode(' ',$tabtext); 
相关问题