用数组值替换字符串中的文本

时间:2014-01-20 15:32:30

标签: php arrays foreach str-replace

新秀需要帮助!

    $some_text = "This red bag will contain green apples.";
    $extracted_array = array("red","bag","green","apples","what","why"); //obtained from database

我想用$ some_text中每个出现的$ extracted_array值替换自身的超链接版本。

所以“这个红包......”变成了

    This <a href="#">red</a> bag...

这就是我写的:

    foreach($extracted_array AS $value) {
    $new_value = '<a href="#">'.$value.'</a>';
    $new_text = str_ireplace($value, $new_value, $some_text);
            }
    print_r($linked_content);

但是这只是用$ extracted_array的循环的最后一个值(即“为什么”)替换每个匹配项

请告诉我如何才能做到这一点。

3 个答案:

答案 0 :(得分:1)

$some_text = "This red bag will contain green apples.";
$extracted_array = array("red","bag","green","apples","what","why");

$expr = sprintf('/%s/i', implode('|', $extracted_array));

echo preg_replace_callback($expr, function($match){
    return sprintf('<a href="#">%s</a>', $match[0]);
}, $some_text);

输出:

This <a href="#">red</a> <a href="#">bag</a> will contain <a href="#">green</a> <a href="#">apples</a>.

答案 1 :(得分:0)

我认为PHP中有更好的功能,但我会告诉你如何使用你的代码:

$some_text = "This red bag will contain green apples.";
$extracted_array = array("red","bag","green","apples","what","why"); //obtained from database

foreach($extracted_array AS $value) {
    $new_value = '<a href="#">'.$value.'</a>';
    $some_text = str_ireplace($value, $new_value, $some_text);
}

print_r($some_text);

您的代码每次$some_text都需要将其保存到$new_text但永远不会更改$some_text $new_text$some_text的原始代码,其中更改了最后一项数组

答案 2 :(得分:0)

您可以创建两个数组,并将它们发送到str_ireplace。但是,如果您正在进行的替换总数非常大,这可能会变得很麻烦。该函数将$ aFind中的字符串替换为$ aReplace中的项目(具有相同的索引)。

$aFind = array("red", "green");
$aReplace = array("<a href='/red.php'>red</a>", "<a href='/green.php'>green</a>");
$newString = str_ireplace($aFind, $aReplace, $some_text);
print($newString);