Dr. House
Dr. House

Reputation: 562

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. How to overcome this?

Upvotes: 0

Views: 737

Answers (1)

miken32
miken32

Reputation: 42763

The most basic approach would be a foreach loop over the check words:

$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. Once you get a bit more familiar with PHP, you could look at something using regular expressions which can get around this problem:

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

Upvotes: 3

Related Questions