2015-12-15 82 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

相关问题