0

如何使用 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";
}

请帮忙!仅提取名称

4

4 回答 4

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";
}
于 2013-05-09T12:46:54.900 回答
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

于 2013-05-09T12:47:58.050 回答
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
于 2013-05-09T12:44:08.520 回答
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";
    }
}
于 2013-05-09T12:53:36.827 回答