简体   繁体   English

替换匹配数组值的字符串中的所有匹配项

[英]Replace all the matches in a string that matches array values

I have a string that I am checking for matches using my array and if there are any matches I want to replace those matches with the same words, but just styled red and then return all the string with the colored words included in one piece. 我有一个字符串,正在使用数组检查是否有匹配项,如果有任何匹配项,我想用相同的单词替换那些匹配项,只是将其设置为红色,然后返回所有包含有彩色单词的字符串。 This is what I have tried: 这是我尝试过的:

$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;

But of course this doesn't work, because the second parameter of str_replace() can't be an array. 但是,这当然是行不通的,因为str_replace()的第二个参数不能是数组。 How to overcome this? 如何克服呢?

The most basic approach would be a foreach loop over the check words: 最基本的方法是对校验字进行foreach循环

$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>";

Note that this does a simple substring search. 请注意,这会执行简单的子字符串搜索。 For example, if you spelled "with" properly, it would still get caught by this. 例如,如果您正确拼写“ with”,它仍然会被该单词抓住。 Once you get a bit more familiar with PHP, you could look at something using regular expressions which can get around this problem: 一旦您对PHP有了更多的了解,就可以使用正则表达式查看可以解决此问题的内容:

$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>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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