tomb
tomb

Reputation: 1827

Wrap tags around certain words

I have an array of words, like this:

array("the", "over", "hen");

I also have a string like this:

"The quick brown fox jumps over the lazy hen"

I want to wrap a tag (strong) around all of the occurrences of the words in the array, but keep the case correct.

For example, using the previous string, it would end up like

<strong>The</strong> quick brown fox jumps <strong>over</strong the lazy <strong>hen</strong>

But, if I have this sentence:

"Hen #2 and ThE oveR reactive cow"

Would look like this:

<strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow

I'm guessing that the answer would use regex, but I'm not very good at that...

Upvotes: 3

Views: 2285

Answers (3)

Teaqu
Teaqu

Reputation: 3263

<?php

$keys = array("the", "over", "hen");

$strings[] = array(
    "The quick brown fox jumps over the lazy hen",
    "Hen #2 and ThE oveR reactive cow. The The. Bus"
);

foreach ($keys as $key)
{
    $cKeys[] = ucfirst($key);
}

for ($i = 0; $i < count($strings); $i++)
{
    foreach ($keys as $key)
    {
        $strings[$i] = preg_replace("/$key/", '<b>$0</b>', $strings[$i]);
    }
    foreach ($cKeys as $key)
    {
        $strings[$i] = preg_replace("/(^|\. )($key)/", '$1<b>$2</b>', $strings[$i]);
    }
}

var_dump($strings);

Upvotes: 0

Ruben Serrate
Ruben Serrate

Reputation: 2783

I think this should work, give it a go :)

$replaceWords=array("the", "over", "hen");

$string="The quick brown fox jumps over the lazy hen";
$string_words=explode(" ", , $string);

foreach $string_words as $i=>$word {
    if (FALSE===array_search(strtolower($word),$replaceWords))
        continue;

    $string_words[i]="<strong>".$strin_words[i]."</strong>";
}
$new_string=implode(" ",$string_words);
echo $new_string;

Upvotes: 0

Bora
Bora

Reputation: 10717

Try following:

$string = 'Then quick brown fox jumps over the lazy hen';
$keys = array('the', 'over', 'hen');

$patterns = array();
foreach($keys as $key)
    $patterns[] = '/\b('.$key.')\b/i';

echo preg_replace($patterns, '<strong>$0</strong>', $string);

Upvotes: 9

Related Questions