编程语言
首页 > 编程语言> > PHP将所有字母大写(包括斜杠后)除了某些单词

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

作者:互联网

我想使用PHP通过大写每个单词来清理一些标题,包括斜杠后的单词.但是,我不想把’和’,”和”这两个词大写.

以下是两个示例字符串:

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

打印所需的会计技术/技术人员和簿记.

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

另外,无视那些因你的$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.

标签:capitalization,php,string
来源: https://codeday.me/bug/20190723/1510863.html