开发者

A PHP Function to Convert ALL CAPS Paragraph String to Regular Case?

I'm on the hunt for a speedy function that will receive a string as a parameter and take this input:

LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. SUSPENDISSE ET QUAM
EU LACUS SCELERISQUE GRAVIDA. DONEC PELLENTESQUE DICTUM DOLOR VEL PULVINAR.
NUNC RHONCUS, ERAT EU SUSCIPIT ALIQUET, RISUS NUNC DICTUM MAGNA, AC ALIQUAM
NIBH NULLA EGET DOLOR. SUSPENDISSE POTENTI. MAECENAS ULLAMCORPE开发者_如何转开发R DIAM NON URNA
VEHICULA ET ULTRICIES TURPIS INTERDUM. PHASELLUS INTERDUM MAGNA ET EROS CURSUS
TRISTIQUE.

And return this output:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse et quam
eu lacus scelerisque gravida. Donec pellentesque dictum dolor vel pulvinar.
Nunc rhoncus, erat eu suscipit aliquet, risus nunc dictum magna, ac aliquam
nibh nulla eget dolor. Suspendisse potenti. Maecenas ullamcorper diam non urna
vehicula et ultricies turpis interdum. Phasellus interdum magna et eros cursus
tristique.

Anyone know of an existing one? Trying to not recreate the wheel if I don't have to.


Well, this comes to mind:

$sentences = array_map('ucfirst',
             array_map('trim',
             array_map('strtolower', explode('.', $input))));
$output = implode('. ', $sentences).'.';

Not fool proof or terribly efficient, but it will get you 98% of the way. You can roll (parts of) your own as you see fit, trading effort for customization/efficiency.

Update: The original answer had a bug: explode left a space at the start of each line, which then had ucfirst fail because the first character was a space. Added trim to the mix to fix that and also make it "more correct".

I also added a trailing . to the output.


Another solution, right from the manual:

function ucfirst_sentence($str)
{
    return preg_replace('/\b(\w)/e', 'strtoupper("$1")', $str);
}

$text = strtowlower($initialText);
echo ucfirst_sentence($text);


Simply use strotolower($string);

Disregard, didn't see you needed sentence casing.

Be careful with this though, as not all periods should have an uppercase letter after them (eg pauses ...), or you may possibly convert names/proper nouns etc to lowercase.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜