Php get value from text file - php

I have this textfile:
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
And I what I'm trying to accomplish is that if I "look" for foo, it returns bar (if I look for bing, it should return bong). A way a tried to accomplish this is first search though the file, return the line with the result, put it in a string and remove everything before the ":" and display the string.
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
$new_str = substr($line, ($pos = strpos($line, ',')) !== false ? $pos + 1 : 0);
}
echo "<br>";
echo "bing should return bong:";
echo $new_str;
But it doesn't work. Up here is just one of the many things I've tried.
Sources:
Many stackoverflow links on and comparable searches:
https://www.google.com/search?client=opera&q=php+remove+everything+after
https://www.google.com/search?client=opera&q=php+search+text+file+return+line
I've asked a question before, but the answers are to "professional" for me, I really need a noob-proof solution/answer. I've been trying to figure it out all day but I just can't get this to work.
Edit:
It's solved! Thank you so much for your time & help, I hope this might be useful to someone else to!

This should work with what you are looking for, I tested it on my server and it seems to fit what you are looking for.
$lines_array = file("file.txt");
$search_string = "bing";
foreach($lines_array as $line) {
if(strpos($line, $search_string) !== false) {
list(, $new_str) = explode(":", $line);
// If you don't want the space before the word bong, uncomment the following line.
//$new_str = trim($new_str);
}
}
echo $new_str;
?>

I would do it this way:
foreach($lines as $line)
{
// explode the line into an array
$values = explode(':',$line);
// trim the whitspace from the value
if(trim($values[1]) == $search)
{
echo "found value for ".$search.": ".$values[1];
// exit the foreach if we found the needle
break;
}
}

$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
Explanation: - $linea var is created before loop, and it will contain search result. If value is found on line - explode string, and make array, get second var from array, put it in search results container variable.

As your data is almost YAML [see lint], you could use a parser in order to get the associated PHP array.
But if can go with your solution as well:
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false){
echo array_pop(explode(":", $line));
}
}

Use fgetcsv:
$bits = array();
if (($handle = fopen('t.txt','r')) !== FALSE) {
while (($data = fgetcsv($handle, 0, ":")) !== FALSE) {
$bits[$data[0]] = $data[1];
}
}
# Now, you search
echo $bits['foo'];
$bits will have a key for each split part, which makes your ultimate goal quite simple. Here is what it looks like:
Array
(
[foo] => bar
[el] => macho
[bing] => bong
[cake color] => blue berry
[mayo] => ello
)

Related

Add text to specific line without removing the exist line in php

I'm trying to add only last name if first name is same
data.txt
Alice Sandy
Alice Nanami
James Watt
Alice Monica
Johann Gauss
to result.txt
Alice Sandy Nanami Monica
James Watt
Johann Gauss
I try with this code
$resultFile = "result.txt";
$search = "Alice";
$lineNumber = false;
if ($handle = fopen($result, "r")) {
$count = 0;
while (($line = fgets($handle, 4096)) !== FALSE and !$lineNumber) {
$count++;
$lineNumber = (strpos($line, $search) !== FALSE) ? $count : $lineNumber;
$isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
}
fclose($handle);
}
if($isExist=="yup"){
$lines = file($resultFile);
$lines[$lineNumber] = $lines[$lineNumber].' '.$lastName;
file_put_contents($result, implode('', $lines));
}else{
$fullName = $firstName.' '.$lastName;
$fileOpen = fopen($result, "a");
fwrite($fileOpen,$fullName);
fclose($fileOpen);
$addBreaker = "\n";
$splResult = new SplFileObject($resultFile, 'a');
$splResult->fwrite($addBreaker);
}
But it give error offset (I'm using PHP 7) and the result is untidy
Alice Sandy Nanami
Monica
James Watt
Johan Gauss
Thanks for help
Another apporach instead of replacing lines would be save every line to an array and then iterate over array and save to the new file. You can also use the same file as an $outputFile.
$inputFile = 'names.txt';
$outputFile = 'result.txt';
$names = [];
if ($handle = fopen($inputFile, "r")) {
$count = 0;
while (($line = fgets($handle, 4096)) !== FALSE) {
$count++;
$lineNames = explode(' ', $line);
$names[$lineNames[0]][] = trim($lineNames[1]);
}
fclose($handle);
}
$handle = fopen($outputFile, 'w');
foreach ($names as $firstName => $lastNames) {
fwrite($handle, $firstName . ' ' . implode(' ', $lastNames) . PHP_EOL);
}
Two additional notes:
Don't use string as boolean value.
$isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
Use just following condition. It's enough
$isExist = (strpos($line, $search) !== FALSE)
If you read lines from file you copy also new lines char, although you can't see them quite well in the output. You should trim all whitespace characters before inserting/replacing etc. to avoid old structure of file.
Use file() to collect the file contents as an array of lines. My snippet starts from there with $lines.
Iterate the array and makes each line modifiable by reference. (&)
Locate the first occurring needle match that not only exists in the line but matches the whole first word so that you don't get false-positive matching.
Then declare the first match as a reference variable (=&) and continue iterating the array. Any subsequent matches will have the delimiting space and second word appended to the reference variable. Then immediate unset the line to be purged from the document.
When done, re-implode the data and stuff the content into the result file.
This is clean, readable, and only needs one loop.
Code: (Demo)
// $lines = file('result.txt', FILE_IGNORE_NEW_LINES);
$lines = [
'Alice Sandy',
'Alice Nanami',
'James Watt',
'Alice Monica',
'Johann Gauss',
'Cooper Alice',
];
$needle = 'Alice';
foreach($lines as $index => &$line) {
if ($needle === strstr($line, ' ', true)) { // check whole first word
if (!isset($firstOccurrence)) {
$firstOccurrence =& $line;
} else {
$firstOccurrence .= strstr($line, ' ');
unset($lines[$index]);
}
}
}
var_export($lines);
// file_put_contents('result.txt', implode(PHP_EOL, $lines));
Output:
array (
0 => 'Alice Sandy Nanami Monica',
2 => 'James Watt',
4 => 'Johann Gauss',
5 => 'Cooper Alice',
)
P.s if you want to know if any rows were changed you could check if the original array is === the new array after looping, or you could just use a boolean flag variable in the else condition.

How can I find a needle in a haystack, and show the entire line?

How can I find a needle in a haystack, and show the entire line?
log.txt :
Log #5731: JohnDoe has arrested JaneDoe
Log #5732: DonDoe has arrested JaneDoe
I want to search for "JohnDoe" and display the whole lineLog #5731: JohnDoe has arrested JaneDoe.
Also, if there's several logs for one person I want to show them all
You could explode your text by newline.
Then search for what you want using array_search method and have the key of that element in the array.
Tho I wouldn't recommend that first solution, if your log is or becomes big (which should be the case for most logs), since the entire log has to be loaded and put into an array. That eats up a massive ammount of resources.
I'd rather do like
<?php
$logfilepath = 'path/to/log.txt';
function searchLog($logfilepath, $searchQuery) {
$fileresource = fopen($logfilepath, 'r');
while (($buffer = fgets($handle)) !== false) {
//now search in buffer
if(strpos($buffer, $searchQuery) !== false) {
return $buffer;
}
}
}
Edit: If you want to find all occurences:
<?php
$logfilepath = 'path/to/log.txt';
function searchLog($logfilepath, $searchQuery) {
$fileresource = fopen($logfilepath, 'r');
$occurences = array();
while (($buffer = fgets($handle)) !== false) {
//now search in buffer
if(strpos($buffer, $searchQuery) !== false) {
$occurences[] = $buffer;
}
}
return $occurences;
}
If the data source is a file and the definition of "entire line" is a newline delimiter, I would use file() to explode the data into an array and then loop through it:
function findLines($file_path, $needle) {
$file_lines = file($file_path);
foreach($file_lines as $line) {
if(strpos($line, $needle) !== false) {
$matching_lines[] = $line;
}
}
return $matching_lines;
}
$needle = 'JohnDoe';
$log_entries = findLines('/path/to/log.txt', $needle);

Retrieve word from string

I have this code:
$getClass = $params->get('pageclass_sfx');
var_dump($getClass); die();
The code above returns this:
string(24) "sl-articulo sl-categoria"
How can I retrieve the specific word I want without mattering its position?
Ive seen people use arrays for this but that would depend on the position (I think) that you enter these strings and these positions may vary.
For example:
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
echo $arr[0];
$arr[0] would return: sl-articulo
$arr[1] would return: sl-categoria
Thanks.
You can use substr for that in combination with strpos:
http://nl1.php.net/substr
http://nl1.php.net/strpos
$word = 'sl-categoria';
$page_class_sfx = $params->get('page_class_sfx');
if (false !== ($pos = strpos($page_class_sfx, $word))) {
// stupid because you already have the word... But this is what you request if I understand correctly
echo 'found: ' . substr($page_class_sfx, $pos, strlen($word));
}
Not sure if you want to get a word from the string if you already know the word... You want to know if it's there? false !== strpos($page_class_sfx, $word) would be enough.
If you know exactly what strings you're looking for, then stripos() should be sufficient (or strpos() if you need case-sensitivity). For example:
$myvalue = $params->get('pageclass_sfx');
$pos = stripos($myvalue, "sl-articulo");
if ($pos === FALSE) {
// string "sl-articulo" was not found
} else {
// string "sl-articulo" was found at character position $pos
}
If you need to check if some word are in string you may use preg_match function.
if (preg_match('/some-word/', 'many some-words')) {
echo 'some-word';
}
But this solution can be used for a small list of needed words.
For other cases i suggest you to use some of this.
$myvalue = $params->get('pageclass_sfx');
$arr = explode(' ',trim($myvalue));
$result = array();
foreach($arr as $key=> $value) {
// This will calculates all data in string.
if (!isset($result[$value])) {
$result[$value] = array(); // or 0 if you don`t need to use positions
}
$result[$value][] = $key; // For all positions
// $result[$value] ++; // For count of this word in string
}
// You can just test some words like follow:
if (isset($result['sl-categoria'])) {
var_dump($result['sl-categoria']);
}

Find specific text until it is found it stops

I was wondering how to do it, this code will as you know get specific line, now I need it to read until a specific text like 55 and stops reading from there. As you can see the log contains some whitespace so what function can I use to read until the code 55?
$row['MtID'] = A unique ID to specify the line where the result is.
So for example the log of the result will be
MM3,67624563 (Unique ID (MtID),233262345599,http://mywebsite.com:8080/web/mm3_pixel.php?sspdata=ams1CIv44qa26LGkchACGKqShLrCtZieSyINNDEuMTkwLjg4LjIwOCgB&vurlid=993211,http://mywebsite.net/sspx?id=69171&sspdata=ams1CIv44qa26LGkchACGKqShLrCtZieSyINNDEuMTkwLjg4LjIwOCgB >> OK
,55
$logfile = file("https://myweb.com/Pixel-Full.php?file=".$country."/".$today."-pixel-response.log");
foreach($logfile as $line_num = > $line) {
if (strpos($line, $row['MtID']) !== false) {
$getresult = strstr(htmlspecialchars($line), 'http://');
echo "<td>".$getresult."</td>";
}
}
This system goes like this, a user request something and nothing found, so on our log, it will post the error link requested by user and the error code for us to know what problem it was. So once the system reads the line and continue to read other line as well until it found the code, it stops
$startline = count($logfile)+1;
foreach($logfile as $line_num => $line) {
if (strpos($line, $row['MtID']) !== false) {
$startline = $line_num;
$getresult = trim(strstr(htmlspecialchars($line), 'http://'));
if (strpos($getresult, ",55") !== false) {
$getresult = substr($getresult,0,strpos($getresult, ",55")+3);
break;
}
}
if ($line_num > $startline) {
$getresult .= trim(htmlspecialchars($line));
if (strpos($getresult, ",55") !== false) {
$getresult = substr($getresult,0,strpos($getresult, ",55")+3);
break;
}
}
}
echo "<td>".$getresult."</td>";
You can use the FILE_SKIP_EMPTY_LINES flag in the file call to skip empty lines and then use array_slice to get the part of the array you need.
$file = array_slice(file("https://myweb.com/Pixel-Full.php?file={$country}/{$today}-pixel-response.log", FILE_SKIP_EMPTY_LINES), 0, $row['MtID']);
foreach($file as $line) {
$result = strstr(htmlspecialchars($line), 'http://');
echo "<td>{$result}</td>";
}
It looks like stopping the execution when a positive match is the biggest trick here. This can be done with a break. (http://php.net/manual/en/control-structures.break.php)
//get the file as a string
$logfile = file_get_contents("https://myweb.com/Pixel-Full.php?file=".$country."/".$today."-pixel-response.log", false);
//make up some rows and catch the false
if ($logfile !== false) {
$logrows = explode("\n", $logfile);
//loop
foreach($logrows as $line) {
if (strpos($line, $row['MtID']) !== false) {
$getresult = strstr(htmlspecialchars($line), 'http://');
echo "<td>".$getresult."</td>";
break;
}
}
}
else echo "Log resource unavailable";
//some memory clearing
unset($logfile);
unset($logrows);
I would suggest for matching sanity that you make sure that the logging format makes the MtID variable something that wouldn't be found in the log text unless its a positive match. Using a UUID or a specific ID format would work.
As you regarded, sometimes, the log line may be divided into three lines while in some other times it is only one line:
// Three lines
http://www.yourwebsite.com/error/33/happycodingneverending&errorcode=33,
succcess=false;
,55
// one line
http://www.yourwebsite.com/error/33/happycodingneverending&errorcode=33,succcess=false;,55
In this case you just have to made a little modification to your code, which, works perfect with only one line example to works with that three lines as follows:
foreach($logfile as $line_num = > $line) {
if (strpos($line, $row['MtID']) !== false) {
$getresult = strstr(htmlspecialchars($line), 'http://');
if(!$getresult){
$theExactLine = $line_num - 2;
$getresult = $logfile[$theExactLine];
}
echo "<td>".$getresult."</td>";
break; // to stop looping.
}
}

parsing a text file in php and retrieving information

I'm trying to parse a basic text file in PHP, but not sure where to begin.
The file contains info such as:
http://pastebin.com/ahqtJzH6
You'll notice that the information I need to capture is split up by new lines. Right now I'm just throwing every new line into a $applicant[] array, but I need to get rid of the preceding text in each line.
I was thinking I probably need to use regex or something to single out just the data I need. Ideas?
Thank you!
Without using regex, you can do this:
$fp = fopen('textfile.txt', 'r');
$return = array();
while ($line = fgets($fp)) {
$parts = explode(':', $line);
$key = trim($parts[0]);
unset($parts[0]);
$value = str_replace("\n", '', implode(':', $parts));
$return[$key] = trim($value);
}
print_r($return);
Would output something like:
Array (
[Applicant SSN] => 123456789
[Applicant Name] => BOB, BOB
...
)
You could use strpos to find the : character and then grab everything after that. You can use trim to get rid of extra whitespace.
$lines = file('textfile.txt');
foreach ($lines as $line) {
$p = strpos($line, ':');
if ($p!==false) {
$key = trim(substr($line, 0, $p));
$value = trim(substr($line, $p+1));
// do whatever with your key & value
}
}

Categories