Hello guys,
In PHP, how can I bold the first two words from a sentence?
Thank you!
Hello guys,
In PHP, how can I bold the first two words from a sentence?
Thank you!
You need to break things down into steps...
1) You have a sentence, like this:
$Sentence = "Hello everybody in the world.";
2) You need to get the first two words. There are two options. You can either split the sentence on every space, or you can find the position of the second space. We'll use the first option for now...
$Words = explode(" ", $Sentence);
3) We re-assemble it all, inserting a bit of HTML to make things bold...
$WordCount = count($Words);
$NewSentence = '';
for ($i = 0; $i < $WordCount; ++$i) {
if ($i < 2) {
$NewSentence .= '<strong>' . $Words[$i] . '</strong> ';
} else {
$NewSentence .= $Words[$i] . ' ';
}
}
echo $NewSentence;
Actually, using the "limit" parameter in the function explode (3rd parameter, optional, check the function spec) you can skip the loop and make your code much simpler:
$words_array = explode(" ",$sentence,3);
$new_sencence = ( count($words_array)>2 )?
"<strong>".$words_array[0]." ".$words_array[1]."</strong> ".$words_array[2] :
"<strong>".$sentence."</strong>"; //sentence is 2 words or less, just bold it
EDIT: took care of sentences with 2 words or less