Reputation: 207
I want to replace all words first character uppercase. I can do this with ucwords but its not unicode encoding. also i need to set delimiters.
this is the, sample text.for replace the each words in, this'text sample' words
I want this text convert to
This İs The, Sample Text.For Replace The Each Words İn, This'Text Sample' Words
After comma, after dot, after space, after comma(not space), after dot(not space)
How can I convert to upper characters with utf-8.
Upvotes: 4
Views: 4811
Reputation: 626903
Here is a code taken from PHP documentation smieat's comment. It should work with Turkish dotted I, and you can add more such letters later to the supportive functions:
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
See IDEONE demo
Upvotes: 0
Reputation: 48721
ucwords()
is a built-in function for this specific problem. You have to set your own delimiters as its second argument:
echo ucwords(strtolower($string), '\',. ');
Outputs:
This Is The, Sample Text.For Replace The Each Words In, This'Text Sample' Words
Upvotes: 4
Reputation: 2363
Not good in Regular expressions so created php function that will do what you want and if you want to add more char you can simply edit this function..
<?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;
}
?>
Upvotes: 1
Reputation: 21437
You can simply use preg_replace_callback
like as
$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);
Upvotes: 2
Reputation: 54841
For this use mb_convert_case
with second parameter MB_CASE_TITLE
.
Upvotes: 2