【问题标题】:What is wrong with this php script?这个 php 脚本有什么问题?
【发布时间】:2011-04-01 14:00:13
【问题描述】:

我想用 bold 中的 $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;
?>

谢谢

【问题讨论】:

  • “这句话”忘了是

标签: php arrays replace foreach explode


【解决方案1】:

首先,pieces 数组中没有五个元素(0 到 4),而只有 4 个(=> 0 到 3)。 接下来,您不需要这样做:

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

什么时候可以做

foreach ($pieces as $item)

改变了第一点,它应该可以工作,但你应该同时改变。

【讨论】:

    【解决方案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;
    

    有两个错误(我认为):

    • 首先,循环指令不正确。
    • 回显的 var 不正确(descrdesc)。

    问候

    【讨论】:

      【解决方案3】:

      没有 $pieces[4]。 0 => 你好; 3 => 诺诺。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        • 2015-10-27
        • 2015-05-24
        • 1970-01-01
        相关资源
        最近更新 更多