PHP preg_split数据

时间:2014-11-12 07:49:18

标签: php

我有.txt文件中的以下数据:

10
std 2798.zip
std 3048.zip
std 3075.zip
std 3123.zip
std 3152.zip
std 3168.zip
std 3171.zip
std 3188.zip
std 3201.zip
-- Clustering --
{{std A.P.1810.zip,std A.P.2221.zip,std 2798.zip,std A.P. 3284.zip,std A.P.2812.zip,std AP 2616.zip,std 3244.zip,std AP 2516.zip},{std 3123.zip,std 3075.zip,std 3270.zip,std 3225.zip,std 3188.zip,std 3203.zip,std 3201.zip,std 3048.zip,std 3168.zip,std AEM_3252.zip,std AP 2427.zip,std 3152.zip,std 3171.zip}}

如何使用preg_split将结果显示为:

Array[0] std 2798.zip
Array[1] std 3048.zip
Array[2] std 3075.zip etc...

同样在--Clustering -

Array[0] {std A.P.1810.zip, std A.P.2221.zip,std 2798.zip etc..},
Array[1] etc....

我的代码是:

echo "ole";

    $string=shell_exec("java -jar plagiarism.jar");
echo $string;
$oparray = preg_split("#[\r\n]+#", trim($string));
echo"<BR><BR>";

foreach ($oparray as $key)
{
    echo $key."   end\n";

    echo"<BR><BR>";

}
 ?>

1 个答案:

答案 0 :(得分:0)

根据操作系统的不同,行结束符分隔符可能是值。通常有“换行”,“回车”和“回车换行”。您需要使用其中任何一个进行拆分。

以下是一个示例:

$string = <<<EOS
10
std 2798.zip
std 3048.zip
std 3075.zip
std 3123.zip
std 3152.zip
std 3168.zip
std 3171.zip
std 3188.zip
std 3201.zip
-- Clustering --
{{std A.P.1810.zip,std A.P.2221.zip,std 2798.zip,std A.P. 3284.zip,std A.P.2812.zip,std AP 2616.zip,std 3244.zip,std AP 2516.zip},{std 3123.zip,std 3075.zip,std 3270.zip,std 3225.zip,std 3188.zip,std 3203.zip,std 3201.zip,std 3048.zip,std 3168.zip,std AEM_3252.zip,std AP 2427.zip,std 3152.zip,std 3171.zip}}
EOS;

$parts  = preg_split("/\r\n|\n|\r/", $string);

// get only those elements which start with std or {{
$result = array_filter($parts, function($element) {
    if (preg_match('/^(std|{{)/', $element)) {
        return $element;
    }
});

var_dump($result);