如何使用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 :(得分: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";
}
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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";
}
}