Jump to content
Larry Ullman's Book Forums

Emphasize Every Other Word In A String


Recommended Posts

Hi all, have just bought Larry's book PHP for the Web Visual Quickstart Guide 4th Ed and have been struggling with the following:

 

- How do I convert every other word in a string so that it is emphasized?

 

I have tried the explode PHP function and using the FOR loop with it but it outputs only every second word.

 

What is needed eg is:

 

This is every other word that is emphasized.

 

Any help would be greatly appreciated.

Link to comment
Share on other sites

$string = 'the quick brown fox jumps over the lazy dog';

$words = explode(' ', $string);

$emphasise = FALSE;

foreach($words as $key => $word){

if ($emphasise){

	$words[$key] = '<strong>' . $word . '</strong>';

}

$emphasise = !$emphasise;

}

echo implode(' ', $words);

  • Upvote 1
Link to comment
Share on other sites

$string = 'the quick brown fox jumps over the lazy dog';

$words = explode(' ', $string);

$emphasise = FALSE;

foreach($words as $key => $word){

if ($emphasise){

	$words[$key] = '<strong>' . $word . '</strong>';

}

$emphasise != $emphasise;

}

echo implode(' ', $words);

 

 

Since != is a comparison operator(not an assignment operator), you'll want to change:

 

$emphasise != $emphasise;

to

 

$emphasise = !$emphasise;

 

 

Also, here's an alternate modified version of Stuart's code which avoids the need for conditional checks and an extra variable:

 

 

$string = 'the quick brown fox jumps over the lazy dog';
$words = explode(' ', $string);

for($i = 1; $i < count($words); $i += 2)
{
$words[$i] = '<strong>' . $words[$i] . '</strong>';
}

echo implode(' ', $words);

 

 

 

If you're going to be using it frequently throughout your code, here's a functionalized form:

 

function emphAltern($string, $start = 1)
{
$words = explode(' ', $string);

for($i = $start; $i < count($words); $i += 2)
{
	$words[$i] = '<strong>' . $words[$i] . '</strong>';
}

return implode(' ', $words);
}

Link to comment
Share on other sites

 Share

×
×
  • Create New...