gpt4 book ai didi

PHP 将除某些单词外的所有字母(包括斜线后)大写

转载 作者:可可西里 更新时间:2023-11-01 00:09:53 28 4
gpt4 key购买 nike

我想使用 PHP 通过将每个单词大写(包括斜杠后面的单词)来清理一些标题。但是,我不想将“and”、“of”和“the”等词大写。

这里有两个示例字符串:

accounting technology/technician and bookkeeping

orthopedic surgery of the spine

应该更正为:

Accounting Technology/Technician and Bookkeeping

Orthopedic Surgery of the Spine


这是我目前拥有的。我不确定如何将内爆与 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]);
}

现在它会将字符串中的所有单词大写,包括我不希望的单词。

最佳答案

好吧,我本来打算尝试对 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]);
}

打印所需的Accounting Technology/Technician and Bookkeeping

您的正则表达式已经匹配字母串,您似乎根本不需要担心斜杠。请注意,单词中间的数字或符号 [如连字符] 也会导致大写。

此外,不要理会那些提示你的 $exclude 数组不够完整的人,你总是可以在遇到它们时添加更多的话。或者只是谷歌列表。

It should be noted that there is no single, agreed-upon "correct" way to determing what should/should not be capitalized in this way.

关于PHP 将除某些单词外的所有字母(包括斜线后)大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103702/

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