user1971853
user1971853

Reputation: 23

how to get only the specific content from a file using PHP.

how to get only the specific content from a file using 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 i.e. (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

$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

Upvotes: 0

Views: 197

Answers (4)

Phellipe Ribeiro
Phellipe Ribeiro

Reputation: 491

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

Upvotes: 0

SomeShinyObject
SomeShinyObject

Reputation: 7821

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

Upvotes: 2

theGreener
theGreener

Reputation: 21

preg_grep returns an array of matching lines, your condition is treating $output4 as a string.

Loop over the array to print out each line and use either substr or str_replace to remove the unwanted characters from the string

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

Upvotes: 2

Viktor S.
Viktor S.

Reputation: 12815

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:

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

Upvotes: 1

Related Questions