替换匹配数组值

时间:2017-02-19 22:21:24

标签: php arrays regex replace

我有一个字符串,我正在使用我的数组检查匹配,如果有任何匹配,我想用相同的单词替换那些匹配,但只是样式为红色,然后返回所有字符串,其中包含一个颜色的单词片。这就是我的尝试:

$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');

  echo '<p>' . str_replace($misspelledOnes,"<span style='color:red'>". $misspelledOnes  . "</span>". '</p>', $string;

但当然这不起作用,因为str_replace()的第二个参数不能是一个数组。如何克服这个?

1 个答案:

答案 0 :(得分:3)

最基本的方法是检查词foreach loop

$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');

foreach ($misspelledOnes as $check) {
    $string = str_replace($check, "<span style='color:red'>$check</span>", $string);
}
echo "<p>$string</p>";

请注意,这会进行简单的子字符串搜索。例如,如果你正确拼写“with”,它仍然会被这个抓住。一旦你对PHP更加熟悉,你可以使用regular expressions查看一些可以解决这个问题的东西:

$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
$check = implode("|", $misspelledOnes);
$string = preg_replace("/\b($check)\b/", "<span style='color:red'>$1</span>", $string);
echo "<p>$string</p>";