2011-04-01 116 views
0

我想用$ sq中的單詞加粗來回顯$ desc。這是我的代碼如下所示:這個PHP腳本有什麼問題?

<?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

「這一句」忘了是 – user666605 2011-04-01 14:01:35

+0

對不起我的英語 – user666605 2011-04-01 14:14:43

回答

4

首先,你不必五行(0-4)在pieces陣列,但只有4(=> 0至3 )。 接下來,你不需要做這個:

foreach (array($pieces[0], $pieces[1],$pieces[2],$pieces[3],$pieces[4]) as $item) 

時,你可以做

foreach ($pieces as $item) 

有了改變,它應該工作的第一點,但你應該改變兩者。

0

沒有$件[4]。 0 =>你好; 3 => nono。

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; 

有兩個錯誤(我認爲):

  • 首先,循環指令是不正確的。
  • 回顯的變量不正確(descrdesc)。

問候

+0

謝謝你這真的幫助! – user666605 2011-04-01 14:08:07