Home > PHP > PHP convert utf-8 ucwords

PHP convert utf-8 ucwords



function my_ucwords($str)
{
mb_internal_encoding('UTF-8');
$string = $str;
return ucwords_specific( mb_strtolower($string, 'UTF-8'), "-'");
}

function ucwords_specific ($string, $delimiters = '', $encoding = NULL)
{
if ($encoding === NULL) { $encoding = mb_internal_encoding();}

if (is_string($delimiters))
{
$delimiters = str_split( str_replace(' ', '', $delimiters));
}

$delimiters_pattern1 = array();
$delimiters_replace1 = array();
$delimiters_pattern2 = array();
$delimiters_replace2 = array();
foreach ($delimiters as $delimiter)
{
$uniqid = uniqid();
$delimiters_pattern1[] = '/'. preg_quote($delimiter) .'/';
$delimiters_replace1[] = $delimiter.$uniqid.' ';
$delimiters_pattern2[] = '/'. preg_quote($delimiter.$uniqid.' ') .'/';
$delimiters_replace2[] = $delimiter;
}

// $return_string = mb_strtolower($string, $encoding);
$return_string = $string;
$return_string = preg_replace($delimiters_pattern1, $delimiters_replace1, $return_string);

$words = explode(' ', $return_string);

foreach ($words as $index => $word)
{
$words[$index] = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding).mb_substr($word, 1, mb_strlen($word, $encoding), $encoding);
}

$return_string = implode(' ', $words);

$return_string = preg_replace($delimiters_pattern2, $delimiters_replace2, $return_string);

return $return_string;
}

 

Ví dụ:


$string = "Áo Sơ Mi Nam"
Nếu dùng dùng hàm ucwords( strtolower($string, 'UTF-8'), "-'"); //output áo Sơ Mi Nam
my_ucwords($string); //output Áo Sơ Mi Nam

Chúng ta chú ý chữ Áoáo viết hoa & viết thường trong 2 hàm trên

PHP Developer
nhantam

Advertisements
Categories: PHP
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: