围绕某些单词包裹标签

时间:2013-09-11 10:02:55

标签: php regex tags

我有一系列的单词,如下:

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

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

3 个答案:

答案 0 :(得分:6)

请尝试以下操作:

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

答案 1 :(得分: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;

答案 2 :(得分: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);