Search String and Return Line PHP - php

I'm trying to search a PHP file for a string and when that string is found I want to return the whole LINE that the string is on. Here is my example code. I'm thinking I would have to use explode but cannot figure that out.
$searchterm = $_GET['q'];
$homepage = file_get_contents('forms.php');
if(strpos($homepage, "$searchterm") !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}

Just read the whole file as array of lines using file function.
function getLineWithString($fileName, $str) {
$lines = file($fileName);
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $str) !== false) {
return $line;
}
}
return -1;
}

You can use fgets() function to get the line number.
Something like :
$handle = fopen("forms.php", "r");
$found = false;
if ($handle)
{
$countline = 0;
while (($buffer = fgets($handle, 4096)) !== false)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
$countline++;
}
if (!$found)
echo "$searchterm not found\n";
fclose($handle);
}
If you still want to use file_get_contents(), then do something like :
$homepage = file_get_contents("forms.php");
$exploded_page = explode("\n", $homepage);
$found = false;
for ($i = 0; $i < sizeof($exploded_page); ++$i)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
}
if (!$found)
echo "$searchterm not found\n";

If you use file rather than file_get_contents you can loop through an array line by line searching for the text and then return that element of the array.
PHP file documentation

You want to use the fgets function to pull an individual line out and then search for the
<?PHP
$searchterm = $_GET['q'];
$file_pointer = fopen('forms.php');
while ( ($homepage = fgets($file_pointer)) !== false)
{
if(strpos($homepage, $searchterm) !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
}
fclose($file_pointer)

Here is an answered question about using regular expressions for your task.
Get line number from preg_match_all()
Searching a file and returning the specified line numbers.

Related

Search for data in CSV with input form

I have a script like that:
$value = $_POST['number']; // searching with input named number
$csv = array();
$file = fopen('data.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
if (in_array($value, $csv)) {
echo "found";
}
else {
echo "not found";
}
fclose($file);
Basically, I always get an answer "not found". Is there any way I could search in CSV file like that?
There's no need to iterate twice, you can get a line from csv and immediately search for $value:
$value = $_POST['number']; // searching with input named number
$file = fopen('data.csv', 'r');
$found = false;
while (($result = fgetcsv($file)) !== false)
{
if (in_array($value, $result)) {
$found = true;
break;
}
}
if ($found) {
echo "found";
}
else {
echo "not found";
}
fclose($file);
AFAIK, in_array only support single dimension array. And your $csv is 2-dimensional. If you have multiple rows of numbers in the CSV file, you'd probably need to search them row by row.
<?php
$value = $_POST['number']; // searching with input named number
$csv = array();
$file = fopen('data.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
$found = false;
foreach ($csv as $row) {
if (in_array($value, $row)) {
$found = true;
break;
}
}
if ($found) {
echo "found";
} else {
echo "not found";
}

Find string in file and display lines number

I'm new at PHP so I'm need help to build this script.
I have a file.txt file with following lines:
aaaa 1234
bbba 1234
aaaa 1236
cccc 1234
aaaa 1238
dddd 1234
I want to find the line with string "aaaa" and print:
String "aaaa" found 3 times at lines: 1, 3, 5.
And better it can print these lines.
I tried this code:
<?
function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
$line_number = '';
if ($file_handler = fopen($filename, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search); //convert file and search string
$line = strtolower($line); //to lowercase
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number .= $i.",";
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or filename";
}
//if no match found
if(count($line_number)){
return substr($line_number, 0, -1);
}else{
return "No match found";
}
}
$output = find_line_number_by_string('file.txt', 'aaaa');
print "String(s) found in ".$output;
?>
But I dont know how to count total of strings found (3) and print each found line.
Thank in advance.
There are lots of ways to do this that produce the same final result but differ in the specifics.
Assuming that your input is not large enough that you are concerned about loading it in memory all at once, one of the most convenient approaches is to use file to read the file's contents into an array of lines, then preg_grep to filter the array and only keep the matching lines. The resulting array's keys will be line numbers and the values will be whole lines that matched, perfectly fitting your requirements.
Example:
$lines = file('file.txt');
$matches = preg_grep('/aaaa/', $lines);
echo count($matches)." matches found.\n";
foreach ($matches as $line => $contents) {
echo "Line ".($line + 1).": ".$contents."\n";
}
$str = "aaaa";
$handle = fopen("your_file.txt", "r");
if ($handle) {
echo "String '".$str."' found at lines : ";
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
echo implode(", ", $arr_lines).".";
}
UPDATE 2 :
$file = "your_file.txt";
$str = "aaaa;";
$arr = count_line_no($file, $str);
if(count($arr)>0)
{
echo "String '".$str."' found at lines : ".implode(", ", $arr).".";;
}
else
{
echo "String '".$str."' not found in file ";
}
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen("your_file.txt", "r");
if ($handle) {
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
}
return $arr_lines;
}
**Try it for solve your problam **
if(file_exists("file.txt")) // check file is exists
{
$f = fopen("file.txt", "r");
// Read line by line until end of file
$row_count = 0;
while(!feof($f))
{
$row_count += 1;
$row_data = fgets($f);
$findme = 'aaaa';
$pos = strpos($row_data, $findme);
if ($pos !== false)
{
echo "The string '$findme' was found in the string '$row_data'";
echo "<br> and line number is".$row_data;
}
else
{
echo "The string '$findme' was not found ";
}
}
fclose($f);
}

PHP: Echo next 2 lines after finding one

<?php
$handle = fopen("wqer.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
**echo fgets($handle).fgets($handle);**
}
}
} else {
echo "Error loading file.";
}
?>
The textfile wqer.txt looks something like that (but it has 12k lines :D):
bike
*aut*
car
ball
mouse
*aut*
light
house
I want from this script to echo next 2 lines after finding the aut line from this file.
So the output should look like this:
car
ball
light
house
Yep sorry, house should be the last one.
Solved, many thanks to Wrikken, simple solution, I almost feel embarrased :)
$found = 0;
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
$found = 2;
continue; // if you don't want "aut" to be printed. remove otherwise.
}
if ($found > 0) {
echo $line;
$found--;
}
}
Add error checking:
$lines = file("wqer.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map('trim', $lines); //in case there are spaces etc. that are not shown
foreach($lines as $key => $val) {
if($val == '*aut*') { //(stripos($val, 'aut') !== false) //to keep similar to how you have it now
echo $lines[$key+1] . "\n" . $lines[$key+2] . "\n";
}
}

How to read multibyte characters from a CSV file using PHP

I have a CSV file which contains a mixture of English and Chinese characters (it is a list of contacts exported from the Mozilla Thunderbird email program). I am trying to create a function which can extract the information from this file. It appears that function fgetcsv() does not support multibyte characters. Since I am running PHP5.2, I do not have access to str_getcsv().
Although the situation above refers to English and Chinese, I am looking for a solution which will work with any language.
Right now I have the function namecards_import_str_getcsv() as my CSV parsing function, which tries to mimic str_getcsv().
function namecards_import_str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
if (!function_exists('str_getcsv')) {
if (is_string($input) && !empty($input)) {
$output = array();
$tmp = preg_split("/".$eol."/",$input);
if (is_array($tmp) && !empty($tmp)) {
while (list($line_num, $line) = each($tmp)) {
if (preg_match("/" . $escape . $enclosure . "/", $line)) {
while ($strlen = strlen($line)) {
$pos_delimiter = strpos($line, $delimiter);
$pos_enclosure_start = strpos($line, $enclosure);
if (is_int($pos_delimiter) && is_int($pos_enclosure_start) && ($pos_enclosure_start < $pos_delimiter)) {
$enclosed_str = substr($line, 1);
$pos_enclosure_end = strpos($enclosed_str, $enclosure);
$enclosed_str = substr($enclosed_str, 0, $pos_enclosure_end);
$output[$line_num][] = $enclosed_str;
$offset = $pos_enclosure_end + 3;
}
else {
if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
$output[$line_num][] = substr($line, 0);
$offset = strlen($line);
}
else {
$output[$line_num][] = substr($line,0,$pos_delimiter);
$offset = (!empty($pos_enclosure_start) && ($pos_enclosure_start < $pos_delimiter))? $pos_enclosure_start : $pos_delimiter + 1;
}
}
$line = substr($line,$offset);
}
}
else {
$line = preg_split("/" . $delimiter . "/", $line);
/*
* Validating against pesky extra line breaks creating false rows.
*/
if (is_array($line) && !empty($line[0])) {
$output[$line_num] = $line;
}
}
}
return $output;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return str_getcsv($input);
}
}
This function is called by the following line of code:
$file = $_SESSION['namecards_csv_file'];
if (file_exists($file->uri)) {
// Load raw csv content into a handler variable.
$handle = fopen($file->uri, "r");
$cardinfo = array();
while (($data = fgets($handle)) !== FALSE) {
$data = namecards_import_str_getcsv($data);
dsm($data);
$cardinfo[] = $data[0];
}
fclose($handle);
}
else {
drupal_set_message(t('CSV file doesn\'t exist'), 'error');
}
In the array of results the strings of Chinese characters are in the correct place in the array by they appear as symbols e.g. "��".
Another method I had tried before this was to simply use fgetcsv() (See below example). But in this case the elements of the returned array were empty.
$file = $_SESSION['namecards_csv_file'];
if (file_exists($file->uri)) {
// Load raw csv content into a handler variable.
$handle = fopen($file->uri, "r");
$cardinfo = array();
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
dsm($data);
$cardinfo[] = $data;
}
fclose($handle);
}
else {
drupal_set_message(t('CSV file doesn\'t exist'), 'error');
}
In case you are interested here is the contents of the CSV file:
First Name,Last Name,Display Name,Nickname,Primary Email,Secondary Email,Screen Name,Work Phone,Home Phone,Fax Number,Pager Number,Mobile Number,Home Address,Home Address 2,Home City,Home State,Home ZipCode,Home Country,Work Address,Work Address 2,Work City,Work State,Work ZipCode,Work Country,Job Title,Department,Organization,Web Page 1,Web Page 2,Birth Year,Birth Month,Birth Day,Custom 1,Custom 2,Custom 3,Custom 4,Notes,
Ben,Gunn,Ben Gunn,Benny,ben1#asdf.com,ben2#asdf.com,,+94 (10) 11111111,+94 (10) 22222222,+94 (10) 33333333,,+94 44444444444,12 Benny Lane,,Beijing,Beijing,100028,China,13 asdfsdfs,,sdfsf,sdfsdf,134323,China,Manager,Sales,Benny Inc,,,,,,,,,,,
乔,康,乔 康,小康,,,,,,,,,,,,,,,北京市朝阳区,,,,,,,,,,,,,,,,,,,
Just writing up as an answer what was figured out in the comments:
fgetcsv is locale sensitive, so make sure to setlocale to a UTF-8 locale.

How to get a recuring parts from a file in php

I have a file file.txt. This file has portions and parts that recur throughout the file. I
am trying to read the parts between the last and the first key words.
I have managed to get the first and the last key words but I can't read the lines between the key words.
Here is my script
$file=file('file.txt');
$begin = 'first_line';
$end='last_line';
foreach ($file as $lineNumber => $line) {
$lineNumber++;
if (strpos($line,$begin))
{
echo $lineNumber.$line."<br/>";
}
elseif (strpos($line,$end))
{
echo $value."<br/>";
}
echo $lineNumber. $line."<br/>";
}
Please some one assist me.
Here you go:
$lines=file('data.txt');
$begin = 'first_line';
$end='last_line';
$switch = false;
$content = "";
foreach ($lines as $line_num => $line) {
if(strpos($line, $begin) !== false) {$switch = true;continue;}
if(strpos($line, $end) !== false) $switch = false;
if(!$switch) continue;
$content .= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
echo $content;
This will do it:
$file = file('file.txt');
$begin = 'first_line';
$end = 'last_line';
$isInside = false;
foreach ($file as $lineNumber => $line)
{
$lineNumber++;
if (!(strpos($line,$begin)===false))
$isInside = true;
if ($isInside)
echo $lineNumber." : ".$line."<br/>";
if (!(strpos($line,$end)===false))
$isInside = false;
}
Some points:
You were displaying everything regardless, my script only shows lines between $begin and $end.
Your comparison is case-sensitive
You had a major bug using strpos and assuming it returns true if it matches. It could also return 0 if the string matches at the beginning,hence using === to catch this. See the disclaimer on the strpos page.
$file=fopen("welcome.txt","r");
while(!feof($file))
{
$open=fgets($file);
print $open;
}
fclose($file);

Categories