简体   繁体   中英

regex help, find first 3 occurrences of a keyword and str_ireplace the content

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM