0

我有这个数据:

920-1063-03@0001D92E@2012-07-02 920-1063-04@00002F5F@2012-07-02 920-1063-04@00002453@2012-07-02 920-1063-03@0001D256@2012-07-02 920-1063-03@0001E225@2012-07-02 920-1063-03@0001E3C1@2012-07-02 920-1063-04@00001EA6@2012-07-02 920-1063-03@0001D316@2012-07-02 920-1063-04@00002A41@2012-07-02 920-1063-04@00001ADA@2012-07-02 920-1063-04@00002DFD@2012-07-02 920-1063-03@0001C595@2012-07-02 920-1063-04@00001C24@2012-07-02 920-1063-04@00002341@2012-07-02 920-1063-04@00001645@2012-07-02 920-1063-04@00001C04@2012-07-02

我试图用@符号分隔。

为此,我有以下代码:

<?php
    $filename = "tru_cage_DSB_sn";
    $fd = fopen ($filename, "r");
    $contents = fread ($fd,filesize ($filename));

    fclose ($fd); 
    $delimiter = "@";
    $splitcontents = explode($delimiter, $contents);
    $counter = "";
    foreach ( $splitcontents as $color ){ 
    $counter = $counter+1;
    echo "<b>Split $counter: </b> $color<br>";
    }
?>

输出将是这样的:

Split 1: 920-1063-03
Split 2: 0001D92E
Split 3: 2012-07-02 920-1063-04
Split 4: 00002F5F
Split 5: 2012-07-02 920-1063-04

但是,我希望拆分也2012-07-02 920-1063-04分成两个字符串,由空格分隔。所以输出应该是这样的?

Split 1: 920-1063-03
Split 2: 0001D92E
Split 3: 2012-07-02
Split 4: 920-1063-04
Split 5: 00002F5F
Split 6: 2012-07-02
Split 7: 920-1063-04

我该如何进一步拆分?

或者,有没有办法将这些数据直接插入到具有 3 列的 mySQL 数据库中?

4

2 回答 2

2

您可以使用preg_split而不是explode拆分由您要使用的任一分隔符组成的正则表达式:

$delimiter = "/@| /";
$splitcontents = preg_split($delimiter, $contents);

此外,您可能应该初始化$counter0空字符串而不是空字符串。


或者,正如Ignacio 评论的那样,使用fgets逐行读取文件。

于 2012-09-03T02:51:12.490 回答
1
<?php

$text = '920-1063-03@0001D92E@2012-07-02 920-1063-04@00002F5F@2012-07-02 920-1063-04@00002453@2012-07-02 920-1063-03@0001D256@2012-07-02 920-1063-03@0001E225@2012-07-02 920-1063-03@0001E3C1@2012-07-02 920-1063-04@00001EA6@2012-07-02 920-1063-03@0001D316@2012-07-02 920-1063-04@00002A41@2012-07-02 920-1063-04@00001ADA@2012-07-02 920-1063-04@00002DFD@2012-07-02 920-1063-03@0001C595@2012-07-02 920-1063-04@00001C24@2012-07-02 920-1063-04@00002341@2012-07-02 920-1063-04@00001645@2012-07-02 920-1063-04@00001C04@2012-07-02';

$matches = preg_split('#[@\s]#msi', $text);

if (count($matches)) {
    $counter = 0;
    foreach ( $matches as $color ){ 
        $counter = $counter++;
        echo "<strong>Split $counter: </strong> $color<br/>\n";
    }
}

?>

输出:

<strong>Split 1: </strong> 920-1063-03<br/>
<strong>Split 2: </strong> 0001D92E<br/>
<strong>Split 3: </strong> 2012-07-02 <br/>
<strong>Split 4: </strong> 920-1063-04<br/>
<strong>Split 5: </strong> 00002F5F<br/>

编辑:我用过preg_split马特提到的,简单得多。

于 2012-09-03T03:01:07.987 回答