php ucword,PHP: ucwords - Manual

Based on code sample originally posted by "Anonymous" on 2005-12-14. The /e modifier is no longer supported by preg_replace(). Rewritten to use preg_replace_callback() instead. Tested with PHP 7.3.

The function below will standardize the capitalization on people's names, addresses, and the titles of reports and essays . Adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function ucwords_title($string, $is_name = false) {

// Exceptions to standard case conversion

if ($is_name) {

$all_uppercase = '';

$all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';

} else {

// Addresses, essay titles ... and anything else

$all_uppercase = 'Us|Ca|Mx|Po|Rr|Se|Sw|Ne|Nw';

$all_lowercase = 'A|And|As|By|In|Of|Or|To';

}

$prefixes = 'Mac|Mc';

$suffixes = "'S";

// Trim whitespace and convert to lowercase

$str = strtolower(trim($string));

// Capitalize all first letters

$str = preg_replace_callback('/\\b(\\w)/', function ($m) {

return strtoupper($m[1]);

}, $str);

if ($all_uppercase) {

// Capitalize acronyms and initialisms (e.g. PHP)

$str = preg_replace_callback('/\\b(' . $all_uppercase . ')\\b/', function ($m) {

return strtoupper($m[1]);

}, $str);

}

if ($all_lowercase) {

// Decapitalize short words (e.g. and)

if ($is_name) {

// All occurrences will be changed to lowercase

$str = preg_replace_callback('/\\b(' . $all_lowercase . ')\\b/', function ($m) {

return strtolower($m[1]);

}, $str);

} else {

// First and last word will not be changed to lower case (i.e. titles)

$str = preg_replace_callback('/(?<=\\W)(' . $all_lowercase . ')(?=\\W)/', function ($m) {

return strtolower($m[1]);

}, $str);

}

}

if ($prefixes) {

// Capitalize letter after certain name prefixes (e.g 'Mc')

$str = preg_replace_callback('/\\b(' . $prefixes . ')(\\w)/', function ($m) {

return $m[1] . strtoupper($m[2]);

}, $str);

}

if ($suffixes) {

// Decapitalize certain word suffixes (e.g. 's)

$str = preg_replace_callback('/(\\w)(' . $suffixes . ')\\b/', function ($m) {

return $m[1] . strtolower($m[2]);

}, $str);

}

return $str;

}

// A name example

print ucwords_title("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);

// Output: Marie-Lou van der Planc-St.John

// A title example

print ucwords_title("to be or not to be");

// Output: "To Be or Not to Be"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值