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
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
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";
}
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
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";
}
}
Related
I want to read all files from a directory but instead of displaying the first character i want to display a certain line, f.e. line 4.
<?php
$directory = "content/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode("|", $contents);
foreach ($items as $item) {
echo "$item[0]";
}
}
}
closedir($dir);
?>
Thanks!
You can use file() function. It reads files into an array, where every line will be an array member, to skip empty lines pass the FILE_SKIP_EMPTY_LINES flag paramater.
For more info consult the docs.
// `$items` is already an array
$items = explode("|", $contents);
// if you want first element of array just:
echo $item[0];
// if you want fourth element of array just:
echo $item[3];
// without `foreach`
Could you show your file structure, please?
Basicaly you can use something like this:
$contents = file_get_contents($filename);
$items = explode("\r\n", $contents); //explode file content
foreach ($items as $item) {
echo $item[3]; //echo your line
}
Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];
$file=fopen("question.txt","r");
while(!feof($file))
{
echo "<h3>". fgets($file)."</h3>"."<br />";
for($i=0;$i<=3;$i++)
{
echo fgets($file)."<br />";
}
}
$lines =file("filename.txt");
and then $lines[4] will return you fifth line.
Find and replace the line. Look at str_replace function at http://php.net/manual/en/function.str-replace.php :)
Maybe a better option in this case... Use the file($path) function to get the lines into an array, then loop through it.
$lines = file($path, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);
I have a .txt file that is like this:
Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end
How could I make PHP to recognize the "tags" and make the content to a new string? Thanks in advance! :D
$fc = file('some_file.txt'); // read file into array
foreach ($fc as $line) {
list($tag, $content) = explode(':', $line, 2);
// do something here
}
Now, are there multiple unrelated sets in each file? If so, you'll have to look for some marker, maybe a new line, and do a reset. Hopefully you can figure this part out on your own.
Some functions for you to check out:
file
file_get_contents
explode
list (not really a function)
Edit: slightly expanding the example:
$fc = file('some_file.txt'); // read file into array
foreach ($fc as $index => $line) {
list($tag, $content) = explode(':', $line, 2);
// do something here
if ('body' == strtolower($tag)) {
$content = join(array_slice($fc, $index + 1, count($fc)));
break;
}
}
More functions for you!
strtolower
join (aka implode)
array_slice
trim - this is not used in my solution, but you may want to use it to trim the newline chars from the end of the lines as returned by file(). Alternatively, you can use the FILE_IGNORE_NEW_LINES flag when calling file(), and more information on that can be found in the PHP Manual entry for file() (also linked above).
Another solution: demo here
<?php
//$sample = file_get_contents('myfile.txt'); // read from file
$sample = "Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end";
$re = '/^(?<tag>\w+):\s?(?<content>.*)$/m';
$matches = null;
if (preg_match_all($re, $sample, $matches))
{
for ($_ = 0; $_ < count($matches['tag']); $_++)
printf("TAG: %s\r\nCONTENT: %s\r\n\r\n", $matches['tag'][$_], $matches['content'][$_]);
}
produces:
TAG: Title
CONTENT: Test
TAG: Author
CONTENT: zad0xsis
TAG: Date
CONTENT: July 13th, 2011
TAG: Body
CONTENT: This is a test post and this can continue until the file end
Thought I'd use named tags just for GPs. Also, if need-be, you can replace the (?<tag>\w+) with something more vague such as (?<tag>.*?) if there could be spaces, numbers, etc.
$file = file("file.txt");
foreach($file as $line)
{
preg_match("|(.*?): (.*?)|", $line, $match);
$tag = $match[1];
$content = $match[2];
}
<?php
$tagValue = array();
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
while(!feof($file))
{
$line = fgets($file);
$tagDelimiter = strpos ($line ,":");
$tag = substr($line,0,$tagDelimiter);
$value = substr($line,$tagDelimiter+1,strlen($line)-$tagDelimiter);
$tagValue[$tag] = $value;
}
fclose($file);
?>
You can access your data : $tagValue["Title"]
you can do this:
$file = file('file.txt');
foreach($file as $line)
{
if(preg_match('/(.*) : (.*)/iUs', $line, $match)
{
$tag = $match[1];
$value = $match[2]
}
}
Use strpos() and substr():
function parse($filename)
{
$lines = file($filename);
$content = array();
foreach ($lines as $line)
{
$posColon = strpos($line, ":");
$tag = substr($line, 0, $posColon);
$body = substr($line, $posColon+1);
$content[$tag] = trim($body);
}
return $content;
}
I have a huge library file containing a word and it's synonyms, this is some words and their synonyms in the format of my library:
aantarrão|1
igrejeiro|igrejeiro|aantarrão|beato
aãsolar|1
desolar|desolar|aãsolar|afligir|arrasar|arruinar|consternar|despovoar|devastar|magoar
aba|11
amparo|amparo|aba|abrigo|achego|acostamento|adminículo|agasalho|ajuda|anteparo|apadrinhamento|apoio|arrimo|asilo|assistência|auxíjlio|auxílio|baluarte|bordão|broquel|coluna|conchego|defesa|égide|encosto|escora|esteio|favor|fulcro|muro|patrocínio|proteção|proteçâo|resguardo|socorro|sustentáculo|tutela|tutoria
apoio|apoio|aba|adesão|adminículo|amparo|aprovação|arrimo|assentimento|base|bordão|coluna|conchego|descanso|eixo|encosto|escora|espeque|fé|fulcro|proteçâo|proteção|refúgio|socorro|sustentáculo
beira|beira|aba|beirada|borda|bordo|cairel|encosta|extremidade|falda|iminência|margem|orla|ourela|proximidade|rai|riba|sopé|vertente
beirada|beirada|aba|beira|encosta|falda|margem|sopé|vertente
encosta|encosta|aba|beira|beirada|clivo|falda|lomba|sopé|subida|vertente
falda|falda|aba|beira|beirada|encosta|fralda|sopé|vertente
fralda|fralda|aba|falda|raiss|raiz|sopé
prestígio|prestígio|aba|auréola|autoridade|domínio|força|halo|importância|influência|preponderância|valia|valimento|valor
proteção|proteção|aba|abrigo|agasalho|ajuda|amparo|apoio|arrimo|asilo|auspiciar|auxílio|bafejo|capa|custódia|defesa|égide|escora|fautoria|favor|fomento|garantia|paládio|patrocínio|pistolão|quartel|refúgio|socorro|tutela|tutoria
sopé|sopé|aba|base|beira|beirada|encosta|falda|fralda|raiz|vertente
vertente|vertente|aba|beira|beirada|declive|encosta|falda|sopé
see aantarrão is a word and below it are the synonyms, I can't think of a way to get the word and the synonyms on an associative array, this is what I'm trying to do:
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
}
?>
nothing, lol, what can I do here ? loop lines until I find an empty line then try to get a new word with the explode ?, help !
Here's some code I cooked up that seems to work.
See the code in action here: http://codepad.org/TVpYgW91
See the code here
UPDATED to read line by line
<?php
$filepointer = fopen("library.txt", "rb");
$words = array();
while(!feof($filepointer)) {
$line = trim(fgets($filepointer));
$content = explode("|", $line);
if (count($content) == 0)
continue;
if (is_numeric(end($content))) {
$word = reset($content);
continue;
}
if (isset($words[$word]))
$words[$word] = array_merge($words[$word], $content);
else
$words[$word] = $content;
}
print_r($words);
So what's the strategy?
fix up the line endings
run through the file line by line
ignore empty lines (count($content))
split the line up on the pipes, if the line has a numerical value for the last value, then this becomes our word
we only get to the last step if none of the other traps got touched, because of the continue statements, so if it is then just split up the words by the pipe and add them to or create the array element.
Try this. I can't remember if array_merge() will work with a null, but the basic idea is that $word is the $key to the assoc array.
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
else if(!empty($explode))
{
$array_sinonimos[$word] = array_merge($synonyms[$word], $explode);
}
}
?>