繁体   English   中英

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

[英]how to get only the specific content from a file using 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";
}

请帮忙! 仅提取名称

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";
}

尝试这个:

$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

下面的代码应该工作:

$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

尝试这个:

$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";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM