[英]how to get only the specific content from a file using PHP.
how to get only the specific content from a file using PHP. 如何使用PHP从文件中仅获取特定内容。
I have a file with content: 我有一个包含内容的文件:
reference 1.pdb
mobile 4r_1.pdb
ignore
fit
mobile 4r_10.pdb
ignore
fit
mobile 4r_22220.pdb
ignore
fit
Now, I want to take all the names ie (output) 现在,我想取所有名称,即(输出)
4r_1
4r_10
4r_22220
in an array and print it. 排列并打印。
The program i have written in php doesn't work properly, can have a look 我用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";
}
Please help! 请帮忙! to extract only the names
仅提取名称
preg_grep returns an array of matching lines, your condition is treating $output4 as a string. preg_grep返回匹配行的数组,您的条件是将$ output4视为字符串。
Loop over the array to print out each line and use either substr or str_replace to remove the unwanted characters from the string 遍历数组以打印出每一行,并使用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";
}
Try this: 尝试这个:
$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));
}
}
Now all the file names (assuming they are file names) are in the array $filenames
现在所有文件名(假设它们是文件名)都在数组
$filenames
Below code should work: 下面的代码应该工作:
$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";
}
}
Note: 注意:
Instead of doing 而不是做
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
You may read a file into array with file() function: 您可以使用file()函数将文件读入数组:
$convert = file('file.txt'); // to read the file
Try this: 尝试这个:
$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.