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

6 comments:

Anonymous said...

Thanks-Much!

Anonymous said...

Thank you, that's a fantastic function.

qishaya said...

Milan create week ended last night with donatella christian louboutin london disregard presenting the ending show of the autumn christian louboutin online frost 2003 italian collections.Donatella, the creative chief of christian boots the house her delayed brother founded, delivered a collection that was, christian louboutin uk as they say, very christian louboutin shoes.First up was the versus limit, louboutin boots the cheaper christian louboutin line. Girls stomped christian louboutin 2010 out with backcombed tresses bearing turquoise leather trousers, christian louboutin uk sale patchwork pullover and blonde fur sliced into stoles and active jackets. christian boots uk But this aggressive hell’s angels look almost seemed a caricature of the christian louboutin boots christian louboutin boots comfort. louboutin sandals Next up was gianni christian louboutin, buy christian louboutin the main collection

shoppingugg said...

Bvlgari is also the thomas jewelry blog producer. Being later, when the surety to high quantity watches, experts usually first essential conditions for all sorts of costumers links london blog
limited sentinel models.

replica ysl shoes said...

If you are British, it's so good that there are Yves Saint Laurent uk, YSL shoes, Let me tell you
YSL shoes
Yves Saint Laurent shoes
Cheap YSL shoes
replica YSL shoes
discount YSL shoes

Mens Leather Blazers For Sale said...

love it thank you
Leather Jackets