正则表达式突出显示它的一部分包含关键字

i've asked same question before here, but now i need to higlight the keywortd in another way, then other part of word. example will be helpful i think

$str = "i like programming very much";
$key = "gram"; 

i need to get something like pro gram ming

$str = "i like <span class='first'>pro</span><span class='second'>gram</span><span class='firs'>ing</span>"

why preg_replace("/([^\s]*?)(".preg_quote($key).")([^\s]*)/iu","<span class="first">$0</span><span class="second">$1</span><span class="first">$2</span>",$str);
doesn't work?

Thanks

There are some errors, the first group is $1 and not $0 and so on. And you embeded ".

so, instead of :

preg_replace("/([^\s]*?)(".preg_quote($key).")([^\s]*)/iu","<span class="first">$0</span><span class="second">$1</span><span class="first">$2</span>",$str);

You have to do :

preg_replace("/([^\s]*?)(".preg_quote($key).")([^\s]*)/iu","<span class='first'>$1</span><span class='second'>$2</span><span class='first'>$3</span>",$str);

You're in PHP, so consider something like:

$words = explode(' ', "quick brown fox");
$out = array_map(process, $words);
return join(' ', $out);

and define

function process($word) {
    $p = strpos($word, 'gram');
    if ($p === FALSE) return $word;
    /// take apart pieces with substr and friends, reformat in HTML, and return them
    $left = substr($word, 0, $p);
    $match = substr($word, $p, strlen('gram'));
    $right = substr($word, $p+strlen('gram'));
    return some_function_of($left, $match, $right);
}

A little more effort, but it does what you want.