primetime 0 Posted August 7, 2011 Report Share Posted August 7, 2011 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. Quote Link to post Share on other sites
Stuart 68 Posted August 7, 2011 Report Share Posted August 7, 2011 $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); 1 Quote Link to post Share on other sites
zanimation 2 Posted August 7, 2011 Report Share Posted August 7, 2011 $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); } Quote Link to post Share on other sites
Stuart 68 Posted August 7, 2011 Report Share Posted August 7, 2011 Haha oops code amended thanks for spotting that one. Quote Link to post Share on other sites
primetime 0 Posted August 7, 2011 Author Report Share Posted August 7, 2011 Many thanks to Stuart and zanimation. Besides the great replies, it also shows there are still a lot I have to learn about PHP and there are many alternate solutions! Thanks again. Quote Link to post Share on other sites
Recommended Posts
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.