Return given string matching line - php

I want write function something like this
getLine($mySteing){
.....
}
How to get line form file(file.txt) given sting include(matching)?. please help
define('COMPANY_FULL_NAME', 'sdfstd') = getLine( "define\(\'COMPANY_FULL_NAME\'\" );
file.txt
define ( 'APP_TITLE', 'Ekdi Inc' );
define('COMPANY_NAME', 'WosdfP');
define('COMPANY_FULL_NAME', 'sdfstd');

the following function will find all the lines that match your string, and it will echo the line number, as $i
function getLine($string)
{
$file = fopen("fle.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$i = 0;
while(!feof($file))
{
$i++;
$line = fgets($file);
$pos = strpos($line, $string);
if( $pos !== false )echo $i.'<br/>';
}
fclose($file);
}
by the way, don't escape characters, don't use \ within the string parameter, as you did in yur code
read http://php.net/manual/en/function.strpos.php

Related

php unable to open file when open and write into file

i try to read a text file line by line and if any line contain "/" then i need to write them into separate file.
example line
CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6
i need to write this as 4 lines, like
CA,T2B,Calgary,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Dover,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6
what i've tried so far is
$file = fopen("test.txt", "r");
while (!feof($file)) {
$my_string = fgets($file);
$special_chars = array("/");
if (array_intersect(str_split($my_string), $special_chars)) {
echo fgets($file) . "<br />";
$myfile = fopen("fileWithFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}else{
echo fgets($file) . "<br />";
$myfile = fopen("fileWithoutFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}
}
fclose($file);
[
file i get from "CA.zip"
how can i do this?
thank you!
You're repeatedly opening and closing fileWithFL.txt and fileWithoutFL.txt, which is inefficient. Better to just open them once before you loop through the input file.
You're also using fgets(), which makes it difficult to parse the input file. Since the input file seems to be in CSV format, you should use fgetcsv().
As for detecting rows that contain multiple cities, I'm looking for the presence of /, splitting on ( or /), removing any trailing ), and trimming the resulting name. That should give you all the cities in a neat array.
$file = fopen("test.txt", "r");
$file_with_fl = fopen("fileWithFL.txt", "w+");
$file_without_fl = fopen("fileWithoutFL.txt", "w+");
while ($a = fgetcsv($file)) {
if ( FALSE == strpos( $a[2], '/' ) ) {
fputcsv( $file_without_fl, $a );
} else {
$cities = preg_split( '/[\(\/]/', $a[2] ); // Split on '(' and '/'
foreach ( $cities as $city ) {
$city = trim(preg_replace('/\)/', '', $city)); // Remove trailing ')' and trim leading and trailing spaces
$a[2] = $city;
fputcsv( $file_with_fl, $a );
}
}
}
Checking for failure of fopen() and fputcsv() left as an exercise for the reader.
You can use file_put_contents(file, string, FILE_APPEND) to add a line to the end of a file.
The rest is just processing the Calgary (Forest Lawn / Dover / Erin Woods) part of your string.
$string = 'CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6';
//test if string needs processing
//if not, write straight to new file
if(strpos($string,'/') === false){
file_put_contents("fileWithoutFL.txt" , $string , FILE_APPEND);
}
//process
else{
//get all the parts split by comma
//$parts[2] is the one you need processing
$parts = explode(',',$string);
//clean up $part[2], replacing ( , ) with *
//then split on the *
$com=explode('*',str_replace(['(','/',')'],'*',$parts[2]));
//loop $com, creating new arrays by replacing $part[2] in the original array
foreach($com as $val){
if($val == '')continue;
//replace $part[2] cleaning up spaces
$parts[2] = trim($val);
//make a new line
$write = implode(',',$parts);
//write to the new file
file_put_contents("fileWithoutFL.txt" , $write , FILE_APPEND);
}
}
Now you can read every line of the original file and output to the new file. (Tip: use SplFileObject)
$file = new SplFileObject("fileWithFL.txt");
while (!$file->eof()) {
$string = $file->fgets();
// ... process here with previous code
}
$file = null;
Not the best answer but its works
$line = file_get_contents("test.txt");
$body = "";
if(false !== strpos($line,"/")) {
$split = preg_split("/[()]+/", $line,-1, PREG_SPLIT_NO_EMPTY);
$contains = explode("/",$split[1]);
$last = explode(",",$split[0]);
$lastvalue = end($last);
$search = array_search($lastvalue,$last);
unset($last[$search]);
$merge = implode(", ", $last);
$body .= $merge . $split[2] . " ";
foreach($contains as $contain) {
$body .= $split[0] . "," . $contain . $split[2] . " ";
}
if(file_put_contents("fileWithFL.txt",$body) !== false) {
echo $body;
} else {
echo "failed";
}
} else {
if(file_put_contents("fileWithoutFL.txt",$line) !== false) {
echo $line;
} else {
echo "failed";
}
}
Output :
CA, T2B,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary ,Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Dover ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6

Search a string and delete the whole line containg the string in php

I need to search a string in .cfg file, and delete the whole line. I'm using file_get_contents to retrieve the the data in .cfg file, and I'm storing it in a variable, searching is good but not knowing how to delete the whole line?
I have a string in following way:
user $username insecure-password $password
I want to search $username and delete the whole line.
Use a little Regex to match the line:
<?php
$file = 'blah
etc
user delboy1978uk insecure-password 123456
etc
etc';
$regex = '#\nuser\s\w+\sinsecure-password\s.+\n#';
preg_match($regex, $file, $matches);
$file = str_replace($matches[0], "\n", $file);
echo $file;
Which outputs:
blah
etc
etc
etc
See it here: https://3v4l.org/BcDWK
With this method you can read each config file line by line search in each line.
$h = fopen('yourfile', 'r') ;
$match = 'username' ;
$output = [] ;
if ($h) {
while (!feof($h)) {
$line = fgets($h);
//your current search function, which search each line
if ( your_search_function($line, $match) === false) {
//array $output will not contain matching lines.
$output[] = $line;
}
}
fclose($h);
//write back to file or do something else with $output
$hw = fopen('yourfile', 'w') ;
if( $hw ) {
foreach( $output as $line ) {
fputs($hw, $line) ;
}
fclose($hw) ;
}
}

Get value from file - php

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'];

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:
$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
$line_result = $line;
}
echo $line;
I have to calculate the result of $line - 1 and echo that result.
But when i do:
$line = $line - 1;
Then it shows $line - 1 and doesn't actually do the calculation.
Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:
$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;
Try replacing
$line = $line - 1;
echo $line
with
$line = ($line -1);
echo $line
This will print 19 instead of 20-1.
I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...
http://php.net/manual/en/function.intval.php
Try this:
$fin = #fopen("path to file", "r");
if ($fin) {
while (!feof($fin)) {
$buffer = fgets($fin);
}
fclose($fin);
}

PHP search text file line by line for two strings then output line

I am trying to search a text file for two values on a line. If both values are present I need to output the entire line. The values I am searching for may not be next to each other which is where I am getting stuck. I have the following code which works well but only for one search value:
<?php
$search = $_REQUEST["search"];
// Read from file
$lines = file('archive.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"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}
?>
Any assistance much appreciated. Many thanks in advance.
Assuming the values you're searching for are separated by a space, and they will both always be present, explode should do the trick:
$search = explode(' ', $_REQUEST["search"]); // change ' ' to ',' if you separate the search terms with a comma, etc.
// Read from file
$lines = file('archive.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[0]) !== false && strpos($line, $search[1] !== false)) {
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}
}
I'll leave it up to you to add some validation to make sure there are always two elements in the $search array, etc.
I also corrected the HTML code. The script looks for two values, $search and $search2. It is using stristr(). For the case-sensitive version of stristr, refer to strstr(). The script will return all lines containing both $search and $search2.
<?php
$search = $_REQUEST["search"];
$search2 = $_REQUEST['search2'];
// Read from file
$lines = file('archive.txt');
echo"<html><head><title>SEARCH RESULTS FOR: $search</title></head><body>";
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(stristr($line,$search) && stristr($line,$search2)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
?>
</body></html>
Just search for your other value also and use && to check for both.
<?php
$search1 = $_REQUEST["search1"];
$search2 = $_REQUEST["search2"];
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search1) !== false && strpos($line, $search2) !== false)
echo"<html><title>SEARCH RESULTS FOR: $search1 and $search2</title><font face='Arial'> $line <hr>";
}
?>
This worked for me. You may define what you like in searchthis aray and it will be displayed with whole line.
<?php
$searchthis = array('1','2','3');
$matches = array();
$handle = fopen("file_path", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
foreach ($searchthis as $param) {
if(strpos($buffer, $param) !== FALSE)
$matches[] = $buffer;
}}
fclose($handle);
}
foreach ($matches as $parts) {
echo $parts;
}
?>

Categories