我在here之前问了同样的问题,但是现在我需要以另一种方式突出显示密钥,然后是其他部分。例子将是有用的我认为
$str = "i like programming very much";
$key = "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?
由于
答案 0 :(得分:1)
您使用的是PHP,请考虑以下内容:
$words = explode(' ', "quick brown fox");
$out = array_map(process, $words);
return join(' ', $out);
并定义
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);
}
多一点努力,但它做你想要的。
答案 1 :(得分:1)
有一些错误,第一组是$ 1而不是$ 0,依此类推。你嵌入了“。
所以,而不是:
preg_replace("/([^\s]*?)(".preg_quote($key).")([^\s]*)/iu","<span class="first">$0</span><span class="second">$1</span><span class="first">$2</span>",$str);
你必须这样做:
preg_replace("/([^\s]*?)(".preg_quote($key).")([^\s]*)/iu","<span class='first'>$1</span><span class='second'>$2</span><span class='first'>$3</span>",$str);