2015-12-15 81 views
2

我想將所有單詞的第一個字符替換爲大寫。我可以用ucwords做到這一點,但它不是unicode編碼。還需要設置分隔符。大寫每個單詞後空格,點,逗號

this is the, sample text.for replace the each words in, this'text sample' words 

我想這個文本轉換爲

This İs The, Sample Text.For Replace The Each Words İn, This'Text Sample' Words 

逗號後點後,空格後,逗號(沒有空格),小數點後(沒有空格)

後,我怎麼能轉換至高字符utf-8,謝謝。

https://eval.in/485321

+1

間接地希望每個字用大寫字母開頭..:d –

+0

它不在「文本樣本」字符串上工作。 –

+0

我還有編碼問題,我添加了鏈接。我怎樣才能通過這些問題 –

回答

2

對於此用途mb_convert_case與第二參數MB_CASE_TITLE

+0

你引用了一個很好的PHP函數。但請注意,它不是緊跟着'dot'或'comma'後面的大寫字符。 – revo

1

您可以簡單地使用preg_replace_callback等作爲

$str = "this is the, sample text.for replace the each words in, this'text sample' words"; 
echo preg_replace_callback('/(\w+)/',function($m){ 
     return ucfirst($m[0]); 
},$str); 

Demo

+0

Downvoters發佈我的答案downvoting的原因 –

+0

但是,您的解決方案適合OP問題,不建議。我們不需要正則表達式來處理字符串大寫。 – revo

1

在這樣創建的PHP函數的正則表達式不太好,會做你想要什麼,如果你想添加更多的炭,你可以簡單地編輯此功能..

<?php 

$str = "this is the, sample text.for replace the each words in, this'text sample' words"; 
echo toUpper($str);//This Is The, Sample Text.For Replace The Each Words In, This'Text Sample' Words 

function toUpper($str) 
{ 
for($i=0;$i<strlen($str)-1;$i++) 
{ 
    if($i==0){ 
     $str[$i]=strtoupper($str[$i].""); 
    } 
    else if($str[$i]=='.'||$str[$i]==' '||$str[$i]==','||$str[$i]=="'") 
    { 
     $str[$i+1]=strtoupper($str[$i+1].""); 

    } 
} 
return $str; 
} 
?> 
+0

我嘗試了它的工作,但我有編碼問題。你能檢查我的叉子嗎? https://eval.in/485321 –

0

ucwords()是針對此特定問題的內置功能。你必須設置自己的分隔符作爲它的第二個參數:

echo ucwords(strtolower($string), '\',. '); 

輸出:

This Is The, Sample Text.For Replace The Each Words In, This'Text Sample' Words

+0

我知道,但ucwords沒有utf-8編碼支持。 –

+0

@KadirÇetintaş它不只是大寫的多字節字符。您需要像在代碼示例中那樣替換它們。在這裏檢查:https://3v4l.org/6vA8R – revo

+0

這不適用於許多PHP版本。 –

0

這裏是PHP documentation smieat's comment採取了代碼。它應與土耳其點綴我的工作,你可以在以後的輔助功能添加更多的此類信件:

function strtolowertr($metin){ 
    return mb_convert_case(str_replace('I','ı',$metin), MB_CASE_LOWER, "UTF-8"); 
} 
function strtouppertr($metin){ 
    return mb_convert_case(str_replace('i','İ',$metin), MB_CASE_UPPER, "UTF-8"); 
} 
function ucfirsttr($metin) { 
    $metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1)); 
return $metin[0].$metin[1]; 
} 

$s = "this is the, sample text.for replace the each words in, this'text sample' words"; 
echo preg_replace_callback('~\b\w+~u', function ($m) { return ucfirsttr($m[0]); }, $s); 
// => This İs The, Sample Text.For Replace The Each Words İn, This'Text Sample' Words 

IDEONE demo

相關問題