我想用粗体中的$ sq中的单词回显$ desc。这就是我的代码:
<?php
$desc = "This a sentence witch contains 4 words on is Hello the other is moto the third is hoto and finally but not least nono.";
$sq = "Hello moto hoto nono";
$pieces = explode(" ", $sq);
foreach (array($pieces[0], $pieces[1],$pieces[2],$pieces[3],$pieces[4]) as $item)
$descr = str_replace($item, "<b>".$item."</b>", $desc);
echo $descr;
?>
由于
答案 0 :(得分:4)
首先,您的pieces
数组中没有五个元素(0到4),但只有4个(=&gt; 0到3)。
接下来,您不需要这样做:
foreach (array($pieces[0], $pieces[1],$pieces[2],$pieces[3],$pieces[4]) as $item)
何时可以
foreach ($pieces as $item)
第一个点改变后,它应该有效,但你应该改变它们。
答案 1 :(得分:2)
试试这个:
$desc = "This a sentence witch contains 4 words on is Hello the other is moto the third is hoto and finally but not least nono.";
$sq = "Hello moto hoto nono";
$pieces = explode(" ", $sq);
foreach ($pieces as $item)
$desc = str_replace($item, "<b>".$item."</b>", $desc);
echo $desc;
有两个错误(我认为):
descr
和desc
)不正确。此致
答案 2 :(得分:0)
没有$ pieces [4]。 0 =&gt;你好; 3 =&gt; NONO。