简体   繁体   English

将str的第一个字符大写,但忽略一个或两个字母词

[英]Turn first character of str capitalized but ignore one or two letter words

I am a newbie and this is a tough one for me. 我是新手,这对我来说很难。

I have a text inside a variable: 我在变量中有一个文本:

$bio = 'text, text, tex ...';

I can use the ucfirst php function to make word in the text start with an uppercase letter. 我可以使用ucfirst php函数使文本中的单词以大写字母开头。

The problem is I don't want the words with one, two or three letters be capitalized becouse it would look unprofessional. 问题是我不希望将带有一个,两个或三个字母的单词大写,因为它看起来不专业。

IMPORTANT: But I want also to keep the letter "I" capitalized since it's proper english grammar. 重要提示:但我也想将字母“ I”大写,因为这是正确的英语语法。

So a text like: this is a text without ucfirst function and i think it needs some capitalizing 像这样的文本:这是没有ucfirst函数的文本,我认为它需要大写

Would look like: This is a Text Without Ucfirst Function and I Think it Needs Some Capitalizing 看起来像:这是没有Ucfirst功能的文本, 认为需要大写

Any ideas? 有任何想法吗?

This will capitalize any word (sequence of English letters) that is 4 or more letters long: 这将大写4个或更多字母的单词(英文字母序列):

$bio = preg_replace_callback('/[a-z]{4,}|\bi\b/i', function($match){
    return ucfirst($match[0]);
}, $bio);

For PHP versions before 5.3: 对于5.3之前的PHP版本:

$bio = preg_replace_callback('/[a-z]{4,}|\bi\b/i',
  create_function('$match', 'return ucfirst($match[0]);'), $bio);

It will leave any shorter words as is such as I and add , and capitalize i . 它将保留任何较短的词,例如Iadd ,并大写i

I would use regex. 我会使用正则表达式。 If you don't want to, you could use split, then iterate over the tokens and use a bunch of if-else, but regex is cooler. 如果不想,可以使用split,然后遍历令牌并使用一堆if-else,但是regex比较凉爽。 ;) ;)

There is a very similar question here: Regex capitalize first letter every word, also after a special character like a dash 这里有一个非常相似的问题:正则表达式每个单词的首字母大写,也要在破折号之后加上特殊字符

嗯?

$bio_x = explode(" ",$bio); if(strlen($bio_x[0]) > 3) $bio = ucfirst($bio); $bio = str_replace(" i "," I ",$bio);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM