webmasters
webmasters

Reputation: 5831

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?

Upvotes: 0

Views: 1198

Answers (3)

Paul
Paul

Reputation: 141819

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.

Upvotes: 3

Sam
Sam

Reputation: 2970

Mmmm so?

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

Upvotes: 0

Turnsole
Turnsole

Reputation: 3472

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

Upvotes: 0

Related Questions