我需要一些帮助我有这个代码大写字符串中每个单词的第一个字符有异常我需要函数忽略异常,如果它在字符串的开头:
function ucwordss($str, $exceptions) {
$out = "";
foreach (explode(" ", $str) as $word) {
$out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
}
return rtrim($out);
}
$string = "my cat is going to the vet";
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);
// Prints: My Cat is Going to the Vet
这就是我正在做的事情:
$string = "my cat is going to the vet";
$ignore = array("my", "is", "to", "the");
echo ucwordss($string, $ignore);
// Prints: my Cat is Going to the Vet
// NEED TO PRINT: My Cat is Going to the Vet
答案 0 :(得分:4)
- return rtrim($out);
+ return ucfirst(rtrim($out));
答案 1 :(得分:3)
这样的事情:
function ucwordss($str, $exceptions) {
$out = "";
foreach (explode(" ", $str) as $key => $word) {
$out .= (!in_array($word, $exceptions) || $key == 0) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
}
return rtrim($out);
}
或者甚至更容易,在你的函数return
之前创建strtoupper第一个字母
答案 2 :(得分:1)
只要总是高估你的第一个词,这样做真的很便宜:
function ucword($word){
return strtoupper($word{0}) . substr($word, 1) . " ";
}
function ucwordss($str, $exceptions) {
$out = "";
$words = explode(" ", $str);
$words[0] = ucword($words[0]);
foreach ($words as $word) {
$out .= (!in_array($word, $exceptions)) ? ucword($word) : $word . " ";
}
return rtrim($out);
}
答案 3 :(得分:0)
你怎么用字符串大写的第一个字母,所以不管你的混音你还会通过
$string = "my cat is going to the vet";
$string = ucfirst($string);
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);
这样你字符串的第一个字母总是大写的
答案 4 :(得分:0)
preg_replace_callback()
将允许您以无环且动态的方式表达条件替换逻辑。考虑这种方法将适当地修改您的示例数据:
代码:(PHP Demo)(Pattern Demo)
$string = "my cat is going to the vet";
$ignore = array("my", "is", "to", "the");
$pattern = "~^[a-z]+|\b(?|" . implode("|", $ignore) . ")\b(*SKIP)(*FAIL)|[a-z]+~";
echo "$pattern\n---\n";
echo preg_replace_callback($pattern, function($m) {return ucfirst($m[0]);}, $string);
输出:
~^[a-z]+|\b(?|my|is|to|the)\b(*SKIP)(*FAIL)|[a-z]+~
---
My Cat is Going to the Vet
您会看到,模式的三个管道部分(按顺序)提出了以下要求:
\b
单词边界元字符),则取消匹配,并继续遍历输入字符串。现在,如果您想特别注意缩略词和带连字符的单词,则只需将'
和-
添加到[a-z]
字符类中,如下所示:{{1} }(Pattern Demo)
如果任何人都有会破坏我的代码片段的边缘情况(例如带有特殊字符的“单词”,需要用[a-z'-]
进行转义),则可以提供它们,也可以提供补丁,但是我的原始解决方案将足以解决发布的问题。