php - str_replace 2个部分有2个不同的结果

时间:2015-08-13 02:25:27

标签: php

我想根据复合词中的单词为单词添加一些html。

例如,让我们来看看#34; doghouse'

让我们说

<div ng-controller="MainController"> <!--insert ng controller here-->
    <div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
        <!-- directive goes here-->
        <newsInfo info="news"></newsInfo>
    </div>
</div>

我希望最终结果产生

$row2['word'] = 'doghouse';
$word = 'dog';
$otherword = 'house';

到目前为止,我的代码无效(我认为我可以<span style="color:blue">dog</span><span style="color:red">house</span> array replace,但显然我无法做到。

str_replace

这是$finalword = str_replace(array($word,$otherword),array("<span style='color:blue'>".$word."</span>","<span style='color:red'>".$word."</span>"),$row2['word']); 错误的选择吗?

2 个答案:

答案 0 :(得分:1)

str_replace是正确的函数,但你并没有真正正确使用它。你设置它的方式,$ row2必须是一个数组,但它不是,它是一个字符串。所以你需要使用另一种方法。您的代码应如下所示:

str_replace($row2, $word.$otherword, "<span style='color:blue'>".$word."</span><span style='color:red'>".$otherword."</span>");

第一个术语($ row2)是你正在搜索的地方,php称之为'haystack'。第二个词$ word。$ otherword就是你要搜索的内容('needle')。第三个术语是你找到它时用'针'代替它的东西。

答案 1 :(得分:0)

我不知道你如何储存你的颜色,但它对你有用吗?

$row2['word'] = 'doghouse';
$words = array('dog','house');
$colors = array('blue', 'red');
$finalword = "";
for ($i = 0; $i < count($words); $i++) {
    $finalword .= "<span style='color:".$colors[$i]."'>".$words[$i]."</span>";
}
echo $finalword;
相关问题