I am trying to search in a txt file using php. It is supposed to search the txt file and display results that it got from the file.
Here is my php code:
<?php
$file = 'my file.txt';
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else {
echo "No matches found";
}
You should use $file to read the file's contents into the $contents variable. You can use get_file_contents for that. Also, it might be useful to turn this into a function, so you can re-use it for other files and search strings:
function searchInFile($file, $searchFor) {
$contents = get_file_contents($file);
if ($contents === false) return array(); // no file, no match
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
preg_match_all($pattern, $contents, $matches));
return $matches[0];
}
$matches = searchInFile('my file.txt', 'concert');
if (count($matches)) {
echo "Found matches:\n" . implode("\n", $matches);
} else {
echo "No matches found";
}
Related
I have the following code in PHP, which searches a file for lines containing a string:
<?php
echo "Results for: ";
echo ($_POST['query']);
echo "<br><br>";
$file = 'completed.db';
$searchfor = ($_POST['query']);
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 "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
?>
In the line, echo implode("\n", $matches[0]); in echos an array, separated by spaces. If I wanted to separate the items by a different string, say $entry = '<br>', how would you do it?
For example, if $matches was
one
two
three
Then, the command should echo:
one<br>two<br>three<br>
Just add the break tag to the string
echo implode("\n<br>", $matches[0]);
And one more to trail since implode only goes between.
echo "<br>";
The following code simply uses implode with a different first argument, bu also adds the separator to the end (as per specification)
$entry = '<br>';
echo implode($entry, $matches[0]).$entry;
So what I want to do is print out all the strings in an array, but seperate them with <p> tags.
I tried this:
echo filter_var( implode( "<p>", $matches[0]), FILTER_SANITIZE_SPECIAL_CHARS); echo "</p>";
but it results in
string1</p>string2</p>string3</p>
instead of
<p>string1</p> <p>string2</p> <p>string3</p>
Any thoughts?
EDIT:
if you need the actual full code, here you go:
<?php
$file = 'logfile.log';
$searchfor = $_POST['name'];
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo filter_var( implode( "<p>", $matches[0]), FILTER_SANITIZE_SPECIAL_CHARS);
}
echo "</p>";
else{
echo "No matches found";
}
?>
You should use htmlspecialchars() for any arbitrary string that you want to safely display on your page, not filter_var().
Here's the complete solution:
foreach ($matches[0] as $str) {
echo '<p>'.htmlspecialchars($str).'</p>';
}
Or, if you really want an (ugly) one-liner:
echo implode('', array_map(function ($str) { return '<p>'.htmlspecialchars($str).'</p>'; }, $matches[0]));
<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
After much help on here, code now looks this ^
Now i am trying to include the code below.
So that it will rename the weapon classes to more userfriendly names.
I have included the two .php files its looking for, but i am unsure to where i place it and if it will even run like it is, wich i doubt.
Could someone
if ($line_type == 'kill') {
include("killfeed_weapon_classnames.php");
include("killfeed_weapon_cleannames.php");
$swap_key = array_search($line_varlist['weapon'], $wcn);
if($swap_key != false) { $line_varlist['weapon'] = $wn[$swap_key]; }
}
Before all of your preg matching and right after $contents use:
$contents = str_replace("(Arma-AH.net)", "(DayZNorway.com)", $contents);
Edited forgot the parenthesis and next question. I am not going to just give you the next part, but look at the example below and follow along this should help you achieve what you want for that next question.
$myArray = array("firstName" =>"sam", "secondName" => "billy", "thirdName" => "sally");
$nameKey = array_search("billy", $myArray);
echo $nameKey;
if($nameKey){
$myArray[$nameKey] = "Tom";
}
print_r($myArray);
<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
This is what i ended up doing, now its hardly pretty, but it works.
Now i need to get the results to show in descending order.
Any chance someone could help me with this?
When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.
Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.
Is there is any php function to display?
I got the output for exact match. But no result for this type of search.
Please help me to find the solution.
you can use stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
So for your situation, if your list was in an array named $values
you could do
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.
Here is the complete code:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
DEMO
This solution is only valid for this pattern of text is like: word1, word2, word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
output:
Bank-List1, Bank-List2
not found
How to find a specific word in a external page using php ?
(dom or pregmatch, or what else ?)
example in foo.com source code with :
span name="abcd"
I want to check if the word abcd is in foo.com in php
if(preg_match('/span\s+name\=\"abcd\"/i', $str)) echo 'exists!';
To check if a string of characters exist:
<?php
$term = 'abcd';
if ( preg_match("/$term/", $str) ) {
// yes it does
}
?>
To check if that string exists as a word in its own right (ie, is not in the middle of a larger word) use word boundary matchers:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/", $str) ) {
// yes it does
}
?>
For a case-insensitive search, add the i flag after the last slash in the regex:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/i", $str) ) {
// yes it does
}
?>
$v = file_get_contents("http://foo.com");
echo substr_count($v, 'abcd'); // number of occurences
//or single match
echo substr_count($v, ' abcd ');
Here are other few ways to find specific word
<?php
$str = 'span name="abcd"';
if (strstr($str, "abcd")) echo "Found: strstr\n";
if (strpos($str, "abcd")) echo "Found: strpos\n";
if (ereg("abcd", $str)) echo "Found: ereg\n";
if (substr_count($str, 'abcd')) echo "Found: substr_count\n";
?>
$name = 'foo.php';
file_get_contents($name);
$contents=$pattern = preg_quote('abcd', '/');
// 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("\n", $matches[0]);
}
else{
echo "not exist word";
}