将字符串拆分为数组然后循环到HTML表中

时间:2013-09-24 17:59:46

标签: php loops

我在下面的示例中有一个从数据库中提取的字符串。我正在尝试将字符串循环到HTML表格中以显示结果,如图中所示。字符串的长度可能不同,但始终采用相同的格式。

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"

_______________________________________________________________________
              |18/05-01/06  | 01/06-06/07 | 06/07-22/08 | 22/08-14/09 |
_______________________________________________________________________
DR Record + 2 | 21.47       | 20.24       | 27.15       | 20.24       |
_______________________________________________________________________
BE Record + 2 | 24.05       | 22.68       |             |             |
_______________________________________________________________________

我尝试的所有东西似乎都不起作用。任何想法都将不胜感激。

这是我到目前为止所尝试的

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"

$parts = preg_split('/\s+/', $string );

$date = array();
$record = array();
$price = array();

foreach($parts as $part) {
    // check date
    if(strpos($part,'-') !== false) {
        $date[] = $part;
    }
    // check price
    elseif(strpos($part, '+') !== false) {
        $record[] = $part;
    }
    // echeck record
    elseif(strpos($part, '.') !== false) { 
        $price[] = $part;
    } 
}

2 个答案:

答案 0 :(得分:1)

$parts = preg_split('/\s+/', $string ); //it returns an array

答案 1 :(得分:0)

<?php
function gsb($string, $start, $end)
{
    $string = " " . $string;
    $ini    = strpos($string, $start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$s= "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68";
$s1=explode(" ",gsb("*".$s,"*"," DR"));//'*' is just used to add an char at first so that we can extract string between it.
$dr=explode(" ",gsb($s," DR Record "," BE Record"));
$be=explode(" ",gsb($s.'*',$dr[count($dr)-2].' '.$dr[count($dr)-1].' ',"*"));//Edited according to comment and you need to access values from $be[2] as $be[0]$$be[1] will contain those two words.
?>

现在你有3个数组$s1$dr&amp; $be包含您需要的所有表值,现在只需根据您的要求使用它。