2013-05-09 88 views
0

如何仅使用PHP从文件中获取特定内容。如何仅使用PHP从文件中获取特定内容。

我有内容的文件:在阵列

reference 1.pdb 
mobile 4r_1.pdb 
ignore 
fit 
mobile 4r_10.pdb 
ignore 
fit 
mobile 4r_22220.pdb 
ignore 
fit 

现在,我想利用所有的名字,即(输出)

4r_1 
4r_10 
4r_22220 

并打印。

我已经用PHP编写的程序无法正常工作,可以看看

$data = file_get_contents('file.txt'); // to read the file 
$convert = explode("\n", $data); // take it in an array 
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array 
if ($output4 !="/mobile/i") 
{ 
print $output4; 
print "\n"; 
} 

请帮帮忙!只提取名称

+0

尝试'var_dump($ output4);' – 2013-05-09 12:41:31

+0

我可能会首先搜索包含'pdb'的行,然后找到最右边的空间,并且爆炸/保留最正确的值。 – Kermit 2013-05-09 12:42:07

+0

在每行中查找'mobile'和substr右侧。 – 2013-05-09 12:44:14

回答

2

试试这个:

$convert = explode("\n", $data); // take it in an array 
$filenames = array(); 


foreach ($convert as $item) { 
    if(strstr($item,'mobile')) { 
     array_push($filenames,preg_replace('/mobile[\s]?([A-Za-z0-9_]*).pdb/','${1}',$item)); 
    } 
} 

现在所有的文件名(假设他们是文件名)在阵列中$filenames

+0

Thankssssssssssss很多:) – user1971853 2013-05-09 12:52:14

+0

没问题。你可能可以使用这个正则表达式。现在它对你发布的内容非常具体。 – SomeShinyObject 2013-05-09 12:54:27

+0

但是当我打印数组时,它以4r_1,4r_1,4r_10的方式打印,其中$ filenames [0] => 4r_1和$ filenames [1] => 4r_1,4r_10。但我想$文件名[0] => 4r_1和$文件名[1] => 4r_10。 :( – user1971853 2013-05-10 06:05:30

1

下面的代码应该工作:

$data = file_get_contents('file.txt'); // to read the file 
$convert = explode("\n", $data); // take it in an array 
$output4 = preg_grep("/mobile/i",$convert); 
if (count($output4)) 
{ 
    foreach ($output as $line) { 

     print $line; // or substr($line, 6) to remove mobile from output 
     print "\n"; 
    } 
} 

注:

而不是做

$data = file_get_contents('file.txt'); // to read the file 
$convert = explode("\n", $data); // take it in an array 

您可以读取一个文件分成数组file()功能:

$convert = file('file.txt'); // to read the file 
2

preg_grep返回匹配行数组,您的条件是将$ output4作为字符串处理。

遍历数组打印出每一行,并请使用SUBSTR或str_replace函数从字符串中删除不需要的字符

$data = file_get_contents('test.txt'); // to read the file 
$convert = explode("\n", $data); // take it in an array 
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array 
foreach($output4 as $entry) { 
    print str_replace("mobile ", "", $entry) . "\n"; 
} 
0

试试这个:

$content = file_get_contents('file.txt'); 
$lines = explode("\n", $content); 
foreach ($lines as $line) { 
    if (preg_match('/^mobile\s+(.+)$/', $line, $match)) { 
     echo $match[1], "\n"; 
    } 
}