gpt4 book ai didi

php - 将字符串中每个单词的第一个字符大写,除了 'and' 、 'to' 等

转载 作者:行者123 更新时间:2023-12-02 20:41:29 25 4
gpt4 key购买 nike

如何使字符串中每个单词的第一个字符大写并接受几个我不想转换的单词,例如 - 和,to 等?

例如,我想要这个 - ucwords('art and design')输出下面的字符串,

“艺术与设计”

是否有可能像 - strip_tags($text, '<p><a>')我们允许在字符串中使用

和 吗?

或者我应该使用其他东西?请指教!

谢谢。

最佳答案

这些都不是真正 UTF8 友好的,所以这是一个可以完美运行的(到目前为止)

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
/*
* Exceptions in lower case are words you don't want converted
* Exceptions all in upper case are any words you don't want converted to title case
* but should be converted to upper case, e.g.:
* king henry viii or king henry Viii should be King Henry VIII
*/
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
foreach ($delimiters as $dlnr => $delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}

用法:

$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos'

关于php - 将字符串中每个单词的第一个字符大写,除了 'and' 、 'to' 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com