I have the following text file called people.txt with the contents:
mikey.mcgurk
Boss Man
michelle.mcgurk
Boss Man 2
I'd like to adjust my PHP script to grab the data on the line that follows each username, so if I was searching for mikey.mcgurk, my script would output Boss Man.
PHP:
<?php //
$file = 'people.txt';
$searchfor = "mikey.mcgurk";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
// write all of this to a text file
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
you can do like this
$contents = file_get_contents($file);
$contents = explode(PHP_EOL, $contents);
if(array_search($searchfor, $contents) !== false){
echo $contents[array_search($searchfor, $contents)+1];
}
You can compare like this:
$contents = file_get_contents($file);
$lines = explode("\n",$contents);
for($i = 0; $i < count($lines); $i++) {
if( $lines[$i] ==$searchfor ) {
echo "Username ".$lines[$i+1];
}
}
Instead of using regular expression you can do this by getting all lines in an array
$lines = explode(PHP_EOL, $contents);
then get keys of results
$keys = array_keys($lines, $pattern);
and increment keys by 1 to get the next line
foreach ($keys as $key) {
echo $lines[++$key];
}
Related
I am working on a PHP code that reads data from text files and it searches for a certain word and echos it, for example, I search for
[Error]
Is it possible to only echo the word I search for only 1 time (aka if the word "Error" is found twice, only echo it once!)
$file = 'filesexample/'.$fileNameNew;
$searchfor = 'error';
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Errors Found:\n";
echo implode("\n", $matches[0]);
}
Can I do this?
You can use the array_unique() PHP's function which remove duplicate values from an array:
if(preg_match_all($pattern, $contents, $matches))
{
$matches[0] = array_unique($matches[0]);
echo "Errors Found:\n";
echo implode("\n", $matches[0]);
}
I need a help with replacing a word from a text file to a link using php
This is my code:
<?php
$search = 'google';
$lines = file('f.txt');
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
echo $search."\n";
echo preg_replace('/google/', '<a href="http://www.google.com/'></a>',$lines);
}
}
?>
I have a little example coded up for you that will illustrate the general idea.
Replace a word
The $_SERVER['PHP_SELF'] variable points to the current file.
if (isset($_GET['replace']) && $_GET['replace'] == 'yes') {
// Define filename
$filename = 'somefile.txt';
// Get file contents
$contents = file_get_contents($filename);
// Replace the word
$contents = str_replace('someword', 'replacewith', $contents);
// Write back to file
file_put_contents($filename, $contents);
}
I have a file that contains something like this:
test:fOwimWPu0eSaNR8
test2:vogAqsfXpKzCfGr
I would like to be able to search the file for say test and it set the string after the : to a variable so it can be displayed, used etc.
Here is the code I have so far for finding 'test' in the file.
$file = 'file.txt';
$string = 'test';
$searchFile = file_get_contents($file);
if (preg_match('/\\b'.$string.'\\b/', $searchFile)) {
echo 'true';
// Find String
} else {
echo 'false';
}
How would I go about doing this?
This should work for you:
Just get your file into an array with file() and then simply preg_grep() all lines, which have the search string before the colon.
<?php
$file = "file.txt";
$search = "test";
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$matches = preg_grep("/^" . preg_quote($search, "/") . ":(.*?)$/", $lines);
$matches = array_map(function($v){
return explode(":", $v)[1];
}, $matches);
print_r($matches);
?>
output:
Array ( [0] => fOwimWPu0eSaNR8 )
I have a text file with the following contents:
---> 12455 ---> 125 ---> KKK
---> 11366 ---> 120 ---> LLL
---> 12477 ---> 120 ---> YYY
I am using the following PHP code to search the file for "---> 124" and I get the following results:
---> 12455 ---> 125 ---> KKK
---> 12477 ---> 120 ---> YYY
but I want the results to be like this:
---> 12455
---> 12477
I want it to return only the first column.
<?php
$file = 'mytext.txt';
$searchfor = '---> ' . "124";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)) {
echo implode($matches[0]);
} else {
echo "No matches found";
}
?>
Change your approach a little bit. Instead of storing the search term and separator in a single string, use two variables.
$sep = '--->';
$searchfor = '124';
$pattern = "/^$sep\s+($searchfor\d+)\s+.*/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo implode(' ', $matches[1])."\n";
}
Outputs:
12455 12477
Demo.
First of all, seperate your concerns:
Read the file
Parse the content
Search
Using Iterators, you can achieve something great here but it will need a deeper understanding of OOP and the iterator interface. What i'll recommend is a simpler approach:
<?php
//Read the file line by line
$handle = fopen('file.txt', 'r');
while(!foef($handle)){
$content = fgets($handle);
//Parse the line
$content = explode('---> ', $content);
//Analyse the line
if($content[1] == 124){
echo $content[0]."\n";
}
}
fclose($handle);
That should be it, just adapt it as you see it, i haven't tested the code here!
change "/^.*$pattern.*\$/m" to "/$pattern\d*/i"
and then echo implode($matches[0]); to foreach($matches[0] as $item) echo "$item<br />\r\n";
If the structure is always as you have shown, then:
Read the file line by line;
explode(); each line by space ;
Read the element [1] of the result;
This seems to be most logical to me. No need for regex in here, because it will work slower then simple explode operation.
Here is an example:
$handle = fopen( 'file.txt', 'r' );
if ( $handle ) {
while ( ( $line = fgets( $handle ) ) !== false ) {
$matches = explode( ' ', $line );
if ( $matches[4] == '124' )
echo $matches[1] . '<br/>';
}
}
try this:
--->\s\d{5}
regex is overkill here, a simple explode('--->', $str) and selecting the first element would suffice
$file = file_get_contents('file.txt');
$lines = explode('---> ', $file);
for($i=1; $i<count($lines); $i=$i+3)
if(strpos($lines[$i], '124')!==false)
$col[$i/3] = /*'--> ' . */$lines[$i];
print_r($col);
That seems to work just fine. Uncomment the comment above if you want the --> included in the output. Also, the resulting $col array is indexed with the row number it is found. Just replace [$i/3] with [] if you don't want that.
Furthering this:
function SearchFileByColumn($contents, $col_num, $search, $col_count = 3) {
$segs = explode('---> ', $contents);
for($i=$col_num; $i<count($segs); $i=$i+$col_count)
if(strpos($segs[$i], $search) !== false)
$res[] = $segs[$i];
return $res;
}
$results = SearchFileByColumn($contents, 1, '124');
I have a php program that looks at a log file and prints it to a page (code below). I don't want the user of said website to be able to look at any line containing a /. I know I could use trim to delete certain characters, but is there a way to delete the entire line? For example, I want to keep something like "Hello" and delete something like /xx.xx.xx.xx connected. All the lines I wish to delete have the same common key, /. Peoples names in said log file have <>s around them, so I must use htmlspecialcharacters
$file = file_get_contents('/path/to/log', true);
$file = htmlspecialchars($file);
echo nl2br($file);
Thanks for your help!
EDIT:
Thanks for all of the answers, currently tinkering with them!
EDIT2:
final code:
<?php
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
$line = htmlspecialchars($line . "\n");
echo nl2br($line);
}
}
?>
Do you mean, like this?
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
// If the line doesn't contain a "/", echo it
echo $line . PHP_EOL;
}
}
For anyone wondering, PHP_EOL is the PHP constant for "end of line" and promotes consistency between different systems (Windows, UNIX, etc.).
If you are iterating through the file line by line you can check with preg_match if the line contains /character and skip the echo if it does. If not, first split them at new line and iterate over that array.
If you don't want to split the file you can probably use preg_replace with a regexp such as (^|\n).*/.*(\n|$) and replace with empty string.
Use the str_replace function -
http://php.net/manual/en/function.str-replace.php. Alternate solution (before escaping the special characters) -
/* pattern /\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/ = /xx.xx.xx.xx connected */
/* pattern will be replaced with "newtext" */
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines as $line)
$correctline = preg_replace( '/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/', 'newtext', $line );
echo $correctline;
}
<?php
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines AS $num => $line)
{
if ( strpos($line, "/") === false ) // Line doesn't contain "/"
{
echo htmlspecialchars($line) . "\n";
}
}
?>