我需要将字符串转换为驼峰大小写,使用以下命令很容易:
mb_convert_case($str, MB_CASE_TITLE, "UTF-8")
但是,如果字符串包含非字母数字字符怎么办:
$str = 'he said "hello world"';
echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
结果是:
He Said "hello World"
但我需要:
He Said "Hello World"
我们该如何处理?
谢谢
使用正则表达式。
如果您只打算使用非重音拉丁字符,它可以像
$str = 'he said "hello WORLD"';
echo preg_replace('/'b([a-z])/e', 'strtoupper(''$1'')', strtolower($str));
这匹配前面有单词边界的任何小写无重音拉丁字母。该字母将替换为其大写等效字母。
如果您希望它也适用于其他语言和脚本,则必须花哨:
$str = 'he said "καλημέρα ΚΌΣΜΕ"'; // this has to be in UTF-8
echo preg_replace('/(?<!'p{L})('p{Ll})/eu',
'mb_convert_case(''$1'', MB_CASE_UPPER, ''UTF-8'')',
mb_convert_case($str, MB_CASE_LOWER, 'UTF-8'));
要理解这一点,您需要参考 PCRE 的 Unicode 功能,并注意我已经在 preg_replace
中添加了 u
修饰符。这匹配任何具有大写等效项的 unicode 字母(模式为 'p{Ll}
),前提是它前面没有任何其他字母(带有模式 'p{L}
的负回溯)。然后,它将其替换为大写等效项。
看到它的实际效果。
更新:看起来您打算仅将空格视为单词边界。这可以通过正则表达式来完成
(?<='s|^)([a-z])
(?<='s|^)('p{Ll})
尝试这样的事情(根据 PHP.net 评论)
$str = 'he said "hello world"';
echo preg_replace('/([^a-z'']|^)([a-z])/ie', '"$1".strtoupper("$2")', strtolower($str));
使用手动! :D在 php.net 上找到
<?php
function ucwordsEx($str, $separator){
$str = str_replace($separator, " ", $str);
$str = ucwords(strtolower($str));
$str = str_replace(" ", $separator, $str);
return $str;
}
/*
Example:
*/
echo ucwordsEx("HELLO-my-NAME-iS-maNolO", "-");
/*
Prints: "Hello My Name Is Manolo"
*/
?>
对于非 unicode 字符,以下将用于将字符串转换为驼峰大小写:
preg_replace('/'b([a-z])/e', 'strtoupper("$1")', strtolower($str));
这是非常简单的代码
echo ucwords('he said '.ucwords('"hello world"')) ;
输出 他说你好世界