我想用突出显示的单词替换字符串中找到的单词,保持其大小写。
示例
$string1 = 'There are five colors';
$string2 = 'There are Five colors';
//replace five with highlighted five
$word='five';
$string1 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string1);
$string2 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string2);
echo $string1.'<br>';
echo $string2;
当前输出:
有
five
种颜色 有five
种颜色
预期输出:
有
five
种颜色 有Five
种颜色
如何做到这一点?
答案 0 :(得分:6)
将preg_replace()
与以下正则表达式一起使用:
/\b($p)\b/i
<强>解释强>
/
- 开始分隔符\b
- 匹配字边界(
- 首次捕获群组的开始$p
- 转义搜索字符串)
- 第一个捕获组的结束\b
- 匹配字边界/
- 结束分隔符i
- 模式修饰符,使搜索不区分大小写 替换模式可以是<span style="background:#ccc;">$1</span>
,其中$1
是反向引用 - 它将包含第一个捕获组匹配的内容(在本例中,它是搜索的实际单词) )
<强>代码:强>
$p = preg_quote($word, '/'); // The pattern to match
$string = preg_replace(
"/\b($p)\b/i",
'<span style="background:#ccc;">$1</span>',
$string
);
$words = array('five', 'colors', /* ... */);
$p = implode('|', array_map('preg_quote', $words));
$string = preg_replace(
"/\b($p)\b/i",
'<span style="background:#ccc;">$1</span>',
$string
);
var_dump($string);
答案 1 :(得分:3)
str_replace - 区分大小写
str_ireplace - class insenstive
http://www.php.net/manual/en/function.str-replace.php
http://www.php.net/manual/en/function.str-ireplace.php
以下是测试用例。
<?php
class ReplaceTest extends PHPUnit_Framework_TestCase
{
public function testCaseSensitiveReplaceSimple()
{
$strings = array(
'There are five colors',
'There are Five colors',
);
$expected = array(
'There are <span style="background:#ccc;">five</span> colors',
'There are <span style="background:#ccc;">Five</span> colors',
);
$find = array(
'five',
'Five',
);
$replace = array(
'<span style="background:#ccc;">five</span>',
'<span style="background:#ccc;">Five</span>',
);
foreach ($strings as $key => $string) {
$this->assertEquals($expected[$key], str_replace($find, $replace, $string));
}
}
public function testCaseSensitiveReplaceFunction()
{
$strings = array(
'There are five colors',
'There are Five colors',
);
$expected = array(
'There are <span style="background:#ccc;">five</span> colors',
'There are <span style="background:#ccc;">Five</span> colors',
);
foreach ($strings as $key => $string) {
$this->assertEquals($expected[$key], highlightString('five', $string, '<span style="background:#ccc;">$1</span>'));
}
}
}
/**
* @argument $words array or string - words to that are going to be highlighted keeping case
* @argument $string string - the search
* @argument $replacement string - the wrapper used for highlighting, $1 will be the word
*/
function highlightString($words, $string, $replacement)
{
$replacements = array();
$newwords = array();
$key = 0;
foreach ((array) $words AS $word)
{
$replacements[$key] = str_replace('$1', $word, $replacement);
$newwords[$key] = $word;
$key++;
$newwords[$key] = ucfirst($word);
$replacements[$key] = str_replace('$1', ucfirst($word), $replacement);
$key++;
}
return str_replace($newwords, $replacements, $string);
}
结果
..
Time: 25 ms, Memory: 8.25Mb
OK (2 tests, 4 assertions)