如何使用PHP从csv格式的字符串中删除其他行?

时间:2016-12-16 00:38:12

标签: php csv string-parsing file-manipulation

嗨我有一个csv格式的字符串,

Lee.leviste,112.198.77.139:44324,12872826,82159116,Thu Dec 15 16:30:18 2016
jelozero23,112.198.78.211:32704,157357727,2952656671,Thu Dec 15 10:59:48 2016
walangmaypake,112.198.78.167:22756,2338395760,27337738911,Thu Dec 15 14:20:12 2016
ROUTING TABLE
Virtual Address,Common Name,Real Address,Last Ref
10.4.0.246,Lee.leviste,112.198.77.139:44324,Thu Dec 15 19:50:26 2016
10.4.0.202,jelozero23,112.198.78.211:32704,Thu Dec 15 19:50:59 2016
10.4.0.250,walangmaypake,112.198.78.167:22756,Thu Dec 15 19:51:00 2016

如何删除从ROUTING TABLE开始到最后一行的那些行并获得此输出?

Lee.leviste,112.198.77.139:44324,12872826,82159116,Thu Dec 15 16:30:18 2016
jelozero23,112.198.78.211:32704,157357727,2952656671,Thu Dec 15 10:59:48 2016
walangmaypake,112.198.78.167:22756,2338395760,27337738911,Thu Dec 15 14:20:12 2016

提前致谢:)

1 个答案:

答案 0 :(得分:0)

如果只需要一个字符串并删除" ROUTING TABLE"之后的所有内容。那会有用。但是看起来您可能想在之后将其用作CSV?你是如何将它转换为字符串的?根据您的使用方式,您可能希望将其从CSV文件转换为数组,然后稍微不同。

<?php 

        $string = "Lee.leviste,112.198.77.139:44324,12872826,82159116,Thu Dec 15 16:30:18 2016
                    jelozero23,112.198.78.211:32704,157357727,2952656671,Thu Dec 15 10:59:48 2016
                    walangmaypake,112.198.78.167:22756,2338395760,27337738911,Thu Dec 15 14:20:12 2016
                    ROUTING TABLE
                    Virtual Address,Common Name,Real Address,Last Ref
                    10.4.0.246,Lee.leviste,112.198.77.139:44324,Thu Dec 15 19:50:26 2016
                    10.4.0.202,jelozero23,112.198.78.211:32704,Thu Dec 15 19:50:59 2016
                    10.4.0.250,walangmaypake,112.198.78.167:22756,Thu Dec 15 19:51:00 2016";

        $string = substr($string, 0, strpos($string, "ROUTING TABLE"));

        echo "-------<br>";
        echo $string;
        echo "<br>-------";

        // OUTPUT:
        // -------
        // Lee.leviste,112.198.77.139:44324,12872826,82159116,Thu Dec 15  16:30:18 2016 jelozero23,112.198.78.211:32704,157357727,2952656671,Thu Dec 15 10:59:48 2016 walangmaypake,112.198.78.167:22756,2338395760,27337738911,Thu Dec 15 14:20:12 2016 
        // -------
    ?>