[英]Capitalize first letter of each word with exception of articles, conjunctions, and prepositions
I am coding a tag system for a custom CMS built with Codeigniter and I'm trying to enforce a particular format.我正在为使用 Codeigniter 构建的自定义 CMS 编写标签系统,并且我正在尝试强制执行特定格式。
Basically, I need the first letter of each word to be capitalized with the exception of the following, which should be lowercase:基本上,我需要每个单词的第一个字母大写,但以下应该是小写的除外:
Furthermore, if the tag starts with one of the above, it should be capitalized.此外,如果标签以上述之一开头,则应大写。
Some examples of properly formatted tags:一些格式正确的标签示例:
So far I just have:到目前为止,我只有:
$tag = 'Lord of the Rings';
$tag = ucwords($tag);
$patterns = array('/A/', '/An/', '/The/', '/And/', '/Of/', '/But/', '/Or/', '/For/', '/Nor/', '/With/', '/On/', '/At/', '/To/', '/From/', '/By/' );
$lowercase = array('a', 'an', 'the', 'and', 'of', 'but', 'or', 'for', 'nor', 'with', 'on', 'at', 'to', 'from', 'by' );
$formatted_tag = preg_replace($patterns, $lowercase, $tag);
// capitalize first letter of string
$formatted_tag = ucfirst($formatted_tag);
echo $formatted_tag;
This produces the correct result of Lord of the Rings , but how can I avoid duplicating the arrays?这会产生指环王的正确结果,但如何避免重复数组? It's tedious matching them up when I add new words.当我添加新词时,将它们匹配起来很乏味。
I'm sure there are some words that should be included that I'm missing, are there any existing functions or classes that I can use?我确定应该包含一些我遗漏的词,是否有任何现有的函数或类可以使用?
You don't need the $lowercase
array if you use a custom callback with preg_replace_callback()
.如果您使用带有preg_replace_callback()
的自定义回调,则不需要$lowercase
数组。 Also, your current method needs word boundaries, otherwise it'll replace Android
with android
or bAnd
with band
.此外,您当前的方法需要单词边界,否则它将用android
替换Android
或用band
替换bAnd
。 Finally, creating N number of regexes for N words is inefficient and not necessary, as this can be done with one single regex.最后,为 N 个单词创建 N 个正则表达式是低效且没有必要的,因为这可以通过一个正则表达式来完成。
I would just keep a words array:我只会保留一个 words 数组:
$words = array('A', 'An', 'The', 'And', 'Of', 'But', 'Or', 'For', 'Nor', 'With', 'On', 'At', 'To', 'From', 'By' );
And create one dynamic regex, complete with word boundaries, like so:并创建一个动态正则表达式,完成单词边界,如下所示:
$regex = '/\b(' . implode( '|', $words) . ')\b/i';
And now replace all of the matches with their lowercase counterpart:现在用小写字母替换所有匹配项:
$formatted_tag = preg_replace_callback( $regex, function( $matches) {
return strtolower( $matches[1]);
}, $tag);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.