ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-23 06:27:34  阅读:278  来源: 互联网

标签:capitalization php string


我想使用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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有