views:

30

answers:

1

Given a block of text, I need to parse it for the existing of a keyword. Then on the first appearance of the keyword, I need to wrap bold tags around it (if it doesn't already have them), on the second appearance of the keyword, italics, and on the third, underline.

Example using the keyword "help":

This is some text with the keyword "help". If you can help, I really appreciate it. Thanks for the help! If there are any more occurrences of the keyword help, I'll ignore them.

Would be rewritten to be...

This is some text with the keyword "<b>help</b>". If you can <em>help</em>, I really appreciate it. Thanks for the <u>help</u>! If there are any more occurrences of the keyword help, I'll ignore them.

+1  A: 

I'm assuming you need a PHP based solution because you mentioned str_ireplace.

You can do it using preg_replace_callback.
This function is similar to preg_replace but calls a user-defined callback function whose return value will be used for replacement.

To keep track of the occurrence number I've used a static variable in the callback function.

$keyword = 'help';

// the callback function
function fun($matches)
{
        static $count = 0;

        // switch on $count and later increment $count.
        switch($count++) {
                case 0: return '<b>'.$matches[1].'</b>';   // 1st time..use bold
                case 1: return '<em>'.$matches[1].'</em>'; 
                case 2: return '<u>'.$matches[1].'</u>';
                default: return $matches[1];              // don't change others.
        }
}

// search for keyword separated by word boundaries.
// if present call the callback function.
$text = preg_replace_callback("/\b($keyword)\b/","fun",$text);

Code In Action

codaddict
Thanks codaddict! Works like a charm!
Scott B
Just had to add the case insensitive qualifier \b/i to the callback...
Scott B