Highlight First Sentence in Each Paragraph

Highlight First Sentence in Each Paragraph

Posted:  February 11, 2013

Highlight First Sentence in Each Paragraph

I recently worked on a custom CMS project, where one of the requirements was to make the first sentence of each paragraph on each page render bold.While there is no 100% sure-fire way to do this, I found the following very helpful in achieving what I was after.First and Foremost, the function that does the dirty work:

function bold_first_sentence($string) {
			$retStr = '';
			preg_match_all('/(?<=[.?!]|^).*?(?=([.?!]).{0,3}[A-Z]|$)/s', $string[1], $matches);
			$mCt = count($matches[0]) - 1;
			for($i = 0; $i < $mCt ; ++$i){
				if($i === 0){
					$retStr .= '<strong>' . trim($matches[0][$i]) . $matches[1][$i] . '</strong> ';
					$retStr .= trim($matches[0][$i]).$matches[1][$i] . ' ';
			return '<p>' . $retStr . '</p>';

Now, since the CMS utilizes classes to render all it’s content, we had to make a slight tweak and use an array for the callback function, for normal usage you will simply use the name of the callback function:

$Content = preg_replace_callback('/<p>(.*?)</p>/', array($this, 'bold_first_sentence'), $parr[0]['Content']);

Here’s hoping you find this useful!

Kevin Pirnie

20+ Years of PC and server maintenance & over 15+ years of web development/design experience; you can rest assured that I take every measure possible to ensure your computers are running to their peak potentials. I treat them as if they were mine, and I am quite a stickler about keeping my machines up to date and optimized to run as well as they can.