2016-02-29 110 views
2

我有一個函數可以讓所有句子的第一個字符大寫,但是由於某種原因,它並沒有對第一個句子的第一個字符進行操作。爲什麼會發生這種情況,我該如何解決?製作所有句子大寫字母的第一個字符

<?php 

function ucAll($str) { 

$str = preg_replace_callback('/([.!?])\s*(\w)/', 
create_function('$matches', 'return strtoupper($matches[0]);'), $str); 
return $str; 

} //end of function ucAll($str) 

$str = ucAll("first.second.third"); 
echo $str; 

?> 

結果:

first.Second.Third 

預期結果:

First.Second.Third 

回答

0

試試這個

function ucAll($str) { 

$str = preg_replace_callback('/([.!?])\s*(\w)|^(\w)/', 
create_function('$matches', 'return strtoupper($matches[0]);'), $str); 
return $str; 

} //end of function ucAll($str) 

$str = ucAll("first.second.third"); 
echo $str; 

|^(\w)是 「或者取得第一個字符」

0

事情是這樣的:

function ucAll($str) { 
      $result = preg_replace_callback('/([.!?])\s*(\w)/',function($matches) { 
      return strtoupper($matches[1] . ' ' . $matches[2]); 
      }, ucfirst(strtolower($str))); 
      return $result; 

      } //end of function ucAll($str) 
$str = ucAll("first.second.third"); 
echo $str; 

輸出:

第一。第二。第三

0

這是因爲您的正則表達式只匹配您定義的標點符號集之後的字符,並且第一個字不符合其中之一。我建議進行以下更改:

首先,此組([?!.]|^)與字符串(^)的開頭以及您試圖替換的(可選)空格和單詞字符之前的標點符號列表相匹配。以這種方式進行設置意味着,如果字符串的開頭有空格,它應該仍然可以工作。其次,使用匿名函數而不是create_functionrecommended,如果您使用的PHP> = 5.3,那麼您希望在這一點上(如果您不是,只需更改函數中的正則表達式仍然可以)。

function ucAll($str) { 
    return preg_replace_callback('/([?!.]|^)\s*\w/', function($x) { 
     return strtoupper($x[0]); 
    }, $str); 
} 
1

因爲正則表達式需要有要的.一個,!?在前方的它它不大寫的第一個字。第一個單詞沒有其中的一個字符。

這將做到這一點:

function ucAll($str) { 
    return preg_replace_callback('/(?<=^|[\.\?!])[^\.]/', function ($match) { 
     return strtoupper($match[0]); 
    }, $str); 
} 

它採用正面看,背後做的.確保一個,!?,或行的開始,是在前期匹配字符串。

0

我已經更新了你的正則表達式,並使用ucwords,而不是像strtoupper作爲

function ucAll($str) { 
    return preg_replace_callback('/(\w+)(?!=[.?!])/', function($m){ 
     return ucwords($m[0]); 
    }, $str); 
} 
$str = ucAll("first.second.third"); 
echo $str; 
相關問題