Someone asked me tonight for a function that capitalized the first word of every sentence in PHP. I thought I could do it with a one line preg_replace, but it didn't want to let me call strtoupper or ucfirst on backreferenced variables for some reason. I didn't really look into it, but I wrote this function instead. It's not necessarily as efficient as I'd like it to be, but it works, and I thought someone might be able to use it.
$text = 'Here is a sentence. here is one not capitalized. and another';
$fixed_text = uc_sentence_start( $text );
echo $fixed_text;
function uc_sentence_start( $value ) {
preg_match_all( '/(\.\s*)([a-z])/m', $value, $matches, PREG_OFFSET_CAPTURE );
for ($i=0; $i< count($matches[0]); $i++) {
$match_pos = $matches[0][$i][1];
$dot_space = $matches[1][$i][0];
$char = $matches[2][$i][0];
$replacement = $dot_space . strtoupper( $char );
$value = substr_replace( $value, $replacement, $match_pos, strlen($replacement) );
}
return $value;
}
Wednesday, November 24, 2004
Subscribe to:
Post Comments (Atom)
3 comments:
Thanks-Much!
Thank you, that's a fantastic function.
love it thank you
Leather Jackets
Post a Comment