3

我有一系列单词,如下所示:

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

我也有这样的字符串:

"The quick brown fox jumps over the lazy hen"

我想strong在数组中所有出现的单词周围加上一个标签 ( ),但要保持大小写正确。

例如,使用前面的字符串,它最终会像

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

但是,如果我有这句话:

"Hen #2 and ThE oveR reactive cow"

看起来像这样:

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

我猜答案会使用正则表达式,但我不是很擅长...

4

3 回答 3

7

尝试以下操作:

$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);
于 2013-09-11T10:16:51.377 回答
0

我认为这应该可行,试一试:)

$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;
于 2013-09-11T10:12:34.987 回答
0
<?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);
于 2013-09-11T10:17:10.423 回答