PHP取代每2秒

时间:2015-11-24 11:51:00

标签: php html

<?php
        $fact_BB = array("[start]", "[mid]", "[end]");
        $fact_HTML   = array("<tr><td class='FactsTableTDOne'><p>", "</p></td><td class='FactsTableTDTwo'><p>", "</p></td></tr>");

        $str_Facts = str_replace($fact_BB, $fact_HTML, $row['facts']);

        echo $str_Facts;
    ?>

是否可以在2 $fact_HTML之间切换?

1. $fact_HTMLone = "code";
2. $fact_HTMLtwo = "code";
3. $fact_HTMLone = "code";
4. $fact_HTMLtwo = "code";
5. $fact_HTMLone = "code";

等。等

2 个答案:

答案 0 :(得分:1)

不确定。使用$fact_HTML[0]$fact_HTML[1]$fact_HTML[n]等,您可以访问$fact_HTML数组。使用2的模数,您始终可以访问数组的每个第二(或第一和第二)元素。

要检查元素是偶数还是奇数,您可以使用:

if ($n % 2 == 0) {
   //even element
} else {
   //odd element
}

此外,您可以使用模2($n % 2)作为n以相同的方式迭代数组。您也可以组合两种变体。

$count = 10; //number of facts
for ($n = 0; $n < $count; $n++) {
    $fact_HTML[$n % 2] = $fact;
}

答案 1 :(得分:0)

您想要实现的是替换某些字符串。我建议这样的解决方案:

<?php
$str_Facts = $row['facts'];
$replacements = array( "[start]" => "<tr><td class='FactsTableTDOne'><p>",
                       "[mid]"   => "</p></td><td class='FactsTableTDTwo'><p>",
                       "[end]"   => "</p></td></tr>" );
foreach ($replacements as $repkey => $repval) {
    $str_Facts = str_replace($repkey,$repval,$str_Facts);
}
echo $str_Facts;
?>

如果你想继续你的方法,你将遍历数组(你必须确保两个数组具有相同数量的元素)。

<?php
$str_Facts = $row['facts'];
for ($i=0;$i<count($fact_BB);$i++) {
    //if you want to switch every uneven, do this:
    if ($i%2!=0) continue;
    $str_Facts = str_replace($fact_BB[$i],$fact_HTML[$i],$str_Facts);
}
echo $str_Facts;
?>