空格,点,逗号后面的每个单词大写

时间:2015-12-15 07:16:19

标签: php regex preg-replace

我想将所有单词替换为第一个字符大写。我可以用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

5 个答案:

答案 0 :(得分:2)

对于此用途mb_convert_case,第二个参数为MB_CASE_TITLE

答案 1 :(得分:2)

ucwords()是针对此特定问题的内置函数。您必须将自己的分隔符设置为第二个参数:

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

输出:

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

答案 2 :(得分:1)

您可以像{/ p>一样使用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

答案 3 :(得分:1)

在正则表达式中不太好,所以创建了php函数,它会做你想要的,如果你想添加更多的char,你可以简单地编辑这个函数..

<?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;
}
?>

答案 4 :(得分:0)

以下是PHP documentation smieat's comment的代码。它应该与土耳其点缀I一起使用,你可以稍后在支持函数中添加更多这样的字母:

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

相关问题