简体   繁体   中英

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.

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.

So a text like: this is a text without ucfirst function and i think it needs some capitalizing

Would look like: This is a Text Without Ucfirst Function and I Think it Needs Some Capitalizing

Any ideas?

This will capitalize any word (sequence of English letters) that is 4 or more letters long:

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

For PHP versions before 5.3:

$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 .

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. ;)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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