UCWORDS功能有例外


ucwords function with exceptions

我需要一些帮助,我有这段代码 大写字符串中每个单词的第一个字符,有例外,我需要函数忽略异常,如果它位于字符串的开头:

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
- return rtrim($out);
+ return ucfirst(rtrim($out));

像这样:

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

通过

始终大写您的第一个单词来非常便宜地做到这一点:

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);
}

你把字符串中的第一个字母大写,所以无论你的混音如何,你仍然会通过

$string = "my cat is going to the vet";
$string = ucfirst($string);
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);

这样,字符串的第一个字母将始终为大写

preg_replace_callback()将允许您以无循环和动态的方式表达条件替换逻辑。 请考虑此方法,该方法将适当地修改示例数据:

代码: (PHP 演示) (模式演示)

$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

您会看到,模式的三个管道部分(按顺序)提出了这些要求:

  1. 如果字符串的开头是单词,请将第一个字母大写。
  2. 如果在"黑名单"中找到"整个单词"(利用'b单词边界元字符),请取消匹配资格并继续遍历输入字符串。
  3. 否则将每个单词的首字母大写。

现在,如果你想特别了解缩略词和连字符词,那么你只需要像这样向[a-z]字符类添加'-[a-z'-](模式演示)

如果有人有一个边缘案例会破坏我的片段(例如需要通过preg_quote()转义的特殊字符的"单词"),你可以提供它们,我可以提供一个补丁,但我的原始解决方案将充分满足发布的问题。