从爆炸的字符串中删除垃圾信息

时间:2012-05-21 12:06:51

标签: php arrays

我正在使用一个API,它向我发送一串信息,由未定义的空格数分隔。当我尝试将其爆炸时,我最终会得到一些仅由空格组成的元素。我尝试过使用foreachpreg_replacepreg_match,几乎所有我能找到的东西都可以摆脱这些空间,但仍有一些空间,奇怪的是,甚至如果我用另一个符号替换这些空格然后爆炸该字符串并删除仅由该符号组成的元素,则仅保留空格元素。此外,任何删除它们的方法都会删除一些,但通常在每个包含有用信息的数组位置之间保留2或3个。

示例:我收到一个看起来像这样的字符串(我使用//来分隔元素):

  

// // // // // // // // // // 1000 // // // // // // // // // // // // // 0   // // // // // // // // 1 // // // // // // // // // 1 // // // // // // // // //   // // // // // // 272 // // // // // // // // // // @ubuntu-10.04-x86 // // //   // basic // // // // // // // // true // // // //运行// // // // 0 //   // // // // // // // // // // // // // // // // // // // // // // // // // // // // //   // 0 // // // // // // // // 1 // // // // // // // // // 2 // // // // // 102   // // // // // // // // 272 // // // // // // // // // @ubuntu-10.04-x86 //   // // // basic // // // // // // // // // // // // // // // // // // // // // // //运行// // //   // 0 // // // // // // // // // // // // 1000 // // // // // // // // // // //   // // // 0 // // // // // // // 1 // // // // // // // // // // 3 // // // //   // 103 // // // // // // // // 0 // // // // // // // // // @ubuntu-10.04-x86   // // // // vswap-256m // // // // // // // // false // // // //停止   // // // // // // //

当我这样做时

$result  = preg_replace('/\s[\s]+/', '-', $result);
$result = preg_split('~-~', $result, -1, PREG_SPLIT_NO_EMPTY);

foreach($result as $item){
    echo "$item //";
}

例如,我最终得到了这个:

  

// // // 1000 // // // 0 // // 1 // // 1 // // // // // // 272 // // ubuntu   //10.04 // x86 // basic // // true // running // 0 // // // // 1000 // // //   // 0 // // 1 // // 2 // 102 // // 272 // // ubuntu //10.04 // x86 //基本//   // true // running // 0 // // // // // // // // // // 0 // // 1 // // 3 // 103 // //   // 0 // // ubuntu //10.04 // x86 // vswap // 256m // //假//停止//   // //

任何人都知道如何从数组中删除那些空元素?

5 个答案:

答案 0 :(得分:3)

您可以使用array_filter根据自己的标准过滤掉元素。

$result = array_filter($result,
                       function($e) { return trim($e) != ''; });

答案 1 :(得分:1)

我可能会在这里遗漏一些东西,但不能只是:

$array = preg_split('/\s\s+/', $input, 0, PREG_SPLIT_NO_EMPTY);

Like this

答案 2 :(得分:0)

首先删除空元素:

$str = preg_replace('%//\s+%', '', $str);

这会从字符串

中删除//<space>

example here

答案 3 :(得分:0)

$match = array();
preg_match_all ( '/[^\s]+/' , $result, $matches);
print_r($match);

答案 4 :(得分:0)

// Where $str is the crazy string.    
$fixed = preg_replace('/\s/', '', $str);
$result = preg_split('~//~', $fixed, -1, PREG_SPLIT_NO_EMPTY);
var_export($result);
相关问题