note 106498 deleted from function.ucfirst by danbrown

From: Date: Tue, 15 Nov 2011 16:27:28 +0000
Subject: note 106498 deleted from function.ucfirst by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-184472@lists.php.net to get a copy of this message
Note Submitter: rommel at rommelsantor dot com ---- I was just noticing all of the lengthy implementations for achieving uppercase sentences (aka, ucsentence or sentencecase). Do yourself a favor and avoid all the extensive code snippets. You can achieve uppercase-sentencing with a single line: <?php function ucsentence($i_str, $i_lowercase = false) { $i_lowercase && ($i_str = strtolower($i_str)); return preg_replace('/((?:^|[\.!?]"?\s+))([a-z])/e', '"$1" . ucfirst("$2")', $i_str); } ?> Of course, there can be no complete automated solution because there may be some terms that you'd prefer stay upper-cased (e.g., proper nouns, initials, abbreviations, etc.), but this does a good job of the most basic requirement of making the first letter of a sentence uppercase. Example: <?php $text = 'this is a test of the "Emergency Broadcast System!" this is only a test! or is it...?'; // // without lowercasing the string first // ucsentence($text); // // Output: // This is a test of the "Emergency Broadcast System!" This is only a test! Or is it...? // // // with lowercasing the string first // ucsentence($text, true); // // Output: // This is a test of the "emergency broadcast system!" This is only a test! Or is it...? // ?>

« previous php.notes (#184472) next »