Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP将除某些单词外的所有字母(包括斜杠后)大写_Php_String_Capitalization - Fatal编程技术网

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

PHP将除某些单词外的所有字母(包括斜杠后)大写,php,string,capitalization,Php,String,Capitalization,我想使用PHP通过大写每个单词来清理一些标题,包括斜杠后面的标题。然而,我不想大写“and”、“of”和“the” 以下是两个示例字符串: 会计技术/技术人员和簿记 脊柱矫形外科 应更正为: 会计技术/技术人员和簿记 脊柱矫形外科 这是我目前拥有的。我不知道如何将内爆与preg_replace_回调结合起来 // Will capitalize all words, including those following a slash $major = implode('/', array_ma

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

以下是两个示例字符串:

会计技术/技术人员和簿记

脊柱矫形外科

应更正为:

会计技术/技术人员和簿记

脊柱矫形外科


这是我目前拥有的。我不知道如何将内爆与preg_replace_回调结合起来

// 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\u 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]);
}

您还需要确保像an和the这样的词是否都是大写的

注意:我想不出任何像这样的术语在开始时以of或and开头,但是在奇怪的数据潜入程序之前更容易修复这样的问题

有一个代码snipplet,我以前在

在php.net函数页面上的注释部分中可以找到ucwords

介词和冠词中的“in”、“on”、“at”等词怎么样?当然……我想它不需要那么包罗万象。现在它将所有内容都大写,但我希望它排除数组中的各种单词。@MattiVirkkunen我相信Jon可以在排除数组中添加元素,如果他愿意,代码只会将单词“不必要”大写。不要再为这个不相关的项目纠缠他了。问题是我不知道如何将斜杠后面的单词大写和排除某些单词结合起来。发布的代码没有达到我想要的效果。@Sammitch:这不是无关紧要的。学习如何简洁准确地描述问题在我们的领域非常重要。完美!谢谢你的帮助。排除数组是我数据库中唯一单词的有限列表…这就是为什么我不觉得有必要将事情过度复杂化。如果我想使用它,我有一个全面的停止词列表-我只是忽略了他们之前所说的,因为这与问题无关。+1,因为我没有看到有必要就排除词的各种排列纠缠OP。@Jon donlaur对以“排除”词开头的字符串提出了一个很好的观点。我只是添加了
ucfirst($major)
来解决这个问题。干杯