PHP - 大写每个单词的第一个字符,除了某些单词

PHP - Capitalise first character of each word expect certain words

我有一批这样的字符串:

tHe iPad hAS gONE ouT of STOCK
PoWER uP YOur iPhone
wHAT moDEL is YOUR aPPLE iPHOne

我想将每个单词的第一个字符大写,其余字符小写 - iPhoneiPad 的任何引用除外。如:

通过使用:

ucwords(strtolower($string));

这可以完成大部分需要的工作,但显然也可以在 iPadiPhone 上完成:

The Ipad Has Gone Out Of Stock
Power Up Your Iphone
What Model Is Your Apple Iphone

我怎样才能实现以下目标:

The iPad Has Gone Out Of Stock
Power Up Your iPhone
What Model Is Your Apple iPhone

您可以为此使用 str_replace。如果前两个参数使用数组,则可以定义一组单词和替换:

echo str_replace(['Ipad', 'Iphone'], ['iPad', 'iPhone'], ucwords(strtolower($string)));

来自文档:

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.

你知道具体的字,而且字数有限,不如在总大小写后还原回去,如下

$string = ucwords(strtolower($string));
$string = str_replace("Ipad","iPad", $string);
$string = str_replace ("Iphone","iPhone", $string);

更通用的解决方案:

<?php

$text = <<<END_TEXT
PoWER uP YOur iPhone
tHe iPad hAS gONE ouT of STOCK 
wHAT moDEL is YOUR aPPLE iPHOne
END_TEXT;

$text = preg_replace(array('/iphone/i', '/iPad/i'), array('iPhone', 'iPad'), $text);
$text = preg_replace_callback('/(\b(?!iPad|iPhone)[a-zA-Z0-9]+)/', 
     function ($match) { return ucfirst(strtolower($match[1])); }, $text);

echo $text;

Demo

在正则表达式中使用否定前瞻来将列出的词从匹配中排除,并通过对匿名函数的回调来操纵其他词。这样,您就可以进行任何类型的操作,例如反转字符串。

不必分别编写要排除的每个单词的小写和大写版本,因此不必将它们写两次,您只需在数组中定义一次并使用 str_ireplace 而不是str_replace 像这样:

$string = "tHe IPHONE and iPad hAS gONE ouT of STOCK";

$excludedWords = array(
    "iPad",
    "iPhone"
);

echo str_ireplace($excludedWords, $excludedWords, ucwords(strtolower($string)));

这会导致

The iPhone And iPad Has Gone Out Of Stock

这会将所有出现的这些词替换为您在数组中定义的版本。

编辑:

记住,使用这个,像"shipadvertise"这样的词将被替换为"shiPadvertise"。 如果你想防止这种情况发生,你可以使用更高级的正则表达式解决方案:

$string = "tHe IPHONE and shipadvertise iPad hAS gONE ouT of STOCK";

$excludedWords = array(
    "iPad",
    "iPhone"
);
$excludedWordsReg = array_map(function($a) { return '/(?<=[\s\t\r\n\f\v])'.preg_quote($a).'/i'; }, $excludedWords);

echo preg_replace($excludedWordsReg, $excludedWords, ucwords(strtolower($string)));

这将正确解析为

The iPhone And Shipadvertise iPad Has Gone Out Of Stock

我使用定界符来确定 ucwords 默认使用的词。

最佳做法是直接在输入字符串上调用 strtolower()(syck 的回答不会这样做)。

我将提供一个纯正则表达式解决方案,该解决方案将适当地针对您的 ipadiphone 单词并将其第二个字母大写,同时将所有其他单词的第一个字母大写。

代码:(PHP Demo) (Pattern Demo)

$strings = [
    "tHe iPad hAS gONE ouT of STOCK
PoWER uP YOur iPhone
wHAT moDEL is YOUR aPPLE iPHOne",           // OP's input string
    "fly the chopper to the helipad.
an audiphone is a type of hearing aid
consisting of a diaphragm that, when
placed against the upper teeth, conveys
sound vibrations to the inner ear"          // some gotcha strings in this element
];

foreach ($strings as $string) {
    echo preg_replace_callback('~\bi\K(?:pad|phone)\b|[a-z]+~', function($m) {return ucfirst($m[0]);}, strtolower($string));
    echo "\n---\n";
}

输出:

The iPad Has Gone Out Of Stock
Power Up Your iPhone
What Model Is Your Apple iPhone
---
Fly The Chopper To The Helipad.
An Audiphone Is A Type Of Hearing Aid
Consisting Of A Diaphragm That, When
Placed Against The Upper Teeth, Conveys
Sound Vibrations To The Inner Ear
---

关于正则表达式模式,可能唯一要提到的部分是 \K 表示 "restart the fullstring match" 或换句话说 "consume and forget the previous character(s) in the current match".

这可能会对你有所帮助..我编写这段代码供我使用并且它对我来说工作得很好...

<?php
function strtocap($arg){
    $finalStr = array();

    $argX = explode(" ",$arg);
    if(is_array($argX)){
        foreach($argX as $v){
            $finalStr[] = ucfirst(strtolower($v));
        }
    }
return implode(" ",$finalStr);
}

$str = "Your unForMated StrInG";
echo strtocap($str);
?>