Jon*_*Jon 3 php string capitalization
我想使用PHP通过大写每个单词来清理一些标题,包括斜杠后的单词.但是,我不想把'和',''和''这两个词大写.
以下是两个示例字符串:
会计技术/技术员和簿记
脊柱骨科手术
应纠正:
会计技术/技术员和簿记
脊椎骨科手术
这就是我现在拥有的.我不确定如何将内爆与preg_replace_callback结合起来.
// Will capitalize all words, including those following a slash
$major = implode('/', array_map('ucwords',explode('/',$major)));
// Is supposed to selectively capitalize words in the string
$major = preg_replace_callback("/[a-zA-Z]+/",'ucfirst_some',$major);
function ucfirst_some($match) {
$exclude = array('and','of','the');
if ( in_array(strtolower($match[0]),$exclude) ) return $match[0];
return ucfirst($match[0]);
}
Run Code Online (Sandbox Code Playgroud)
现在它将字符串中的所有单词大写,包括我不想要的单词.
好吧,我打算尝试递归调用ucfirst_some(),但是你的代码似乎没有第一行就可以正常工作.即:
<?php
$major = 'accounting technology/technician and bookkeeping';
$major = preg_replace_callback("/[a-zA-Z]+/",'ucfirst_some',$major);
echo ucfirst($major);
function ucfirst_some($match) {
$exclude = array('and','of','the');
if ( in_array(strtolower($match[0]),$exclude) ) return $match[0];
return ucfirst($match[0]);
}
Run Code Online (Sandbox Code Playgroud)
打印所需的Accounting Technology/Technician and Bookkeeping.
你的正则表达式已匹配字母串,你似乎根本不需要担心斜杠.请注意,单词中间的数字或符号[如连字符]也会导致大小写.
此外,无视人们对你的$exclude阵列不够完整,你可以随时添加更多单词.或者只是谷歌的列表.
应该指出的是,没有单一的,商定的"正确"方式来确定以这种方式应该/不应该资本化的内容.