2017-06-14 35 views
0

我有一個文件作爲數組 '行號'=>'它的內容'; 現在我需要一種方法來刪除行只包含數字(不含字母或特殊caracters) 我做到了由線的長度,但這種方法是不恰當的,因爲它可能會刪除某些內容如何過濾僅包含數字的數組值

/*count file lines*/ 
$linecount = 0; 
$handle = fopen($file, "r"); 
while(!feof($handle)){ 
    $line = fgets($handle); 
    $linecount++; 
} 
fclose($handle); 

for($i=0; $i<=($linecount*2)-4;$i++) { 
    $length = strlen((string)$text[0][$i]); 
    if ($length >5) 
    { 
     echo ($text[0][$i] .'</br>'); 
    } 

} 

is_numric沒有工作,我認爲這是因爲數字前的空間

+0

怎麼樣使用'is_numeric($ value)' – Rasclatt

+0

已經嘗試過,但沒有工作,我猜這是因爲在 –

+0

之前有空格嘗試使用這個 – hungrykoala

回答

1

我修改的第二行。不明白爲什麼$長度> 5,應該$長度> 0

strlen(trim((string)$text[0][$i])); 

for($i=0; $i<=($linecount*2)-4;$i++) { 
$length = strlen(trim((string)$text[0][$i])); 
if ($length >0) 
    { 
     echo ($text[0][$i] .'</br>'); 
    } 

} 
1

請試試這個

$keys=array_filter(array_keys($array1), "is_numeric"); 
$out =array_diff_key($array1,array_flip($keys)); 
print_r($out); 
1

試試這個:

$pattern = '/^[0-9 ]+$/'; 

if (!preg_match ($pattern, $text)) 
{ 
    echo 'allowed'; 
} 

here

1

由於有鑑於我已經根據給出的描述,假定數據輸入這個答案沒有示例數據 - 它可能沒有相似到實際的數據。

我使用的輸入文件具有以下數據線 - 字符的混合和數字

abc23 
123 
89 
gh46m 
12 34 56 


$file='c:/temp/src.txt'; 

$lines=array_filter(file($file), function($item){ 
    $pttn='@^[0-9\s]{1,}[email protected]'; 
    preg_match($pttn, $item ,$matches); 
    return count($matches) > 0 ? true : false; 
}); 

echo '<pre>',print_r($lines,true),'</pre>'; 

此輸出以下:

Array 
(
    [1] => 123 

    [2] => 89 

    [4] => 12 34 56 
) 

如果space被視爲一個特殊字符,然後只需通過刪除\s來修改正則表達式模式,並且應該只匹配數字

相關問題