Jump to content
Larry Ullman's Book Forums

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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...