Wednesday, November 24, 2004

Capitalizing the first word of every sentence in PHP

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

3 comments:

Anonymous said...

Thanks-Much!

Anonymous said...

Thank you, that's a fantastic function.

Mens Leather Blazers For Sale said...

love it thank you
Leather Jackets