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'];
Related
i want search string in text file. find result and return after : character.
input is alex
text file include this item
alex:+123
david:+1345
john:+1456
output is +123
$input = "alex";
file_get_contents("TextFilePath");
//in this step i don't know what should i do
Maybe not the best solution, but you can use file and loop on the array. explode each line to see if the needle was present.
function findInAFile($filename, $needle) {
// read file split on newline
$lines = file($filename);
// check each line and return first occurence
foreach ($lines as $line) {
$arr = explode($needle, $line, 2);
if (isset($arr[1])) {
return $arr[1];
}
}
}
echo findInAFile('file.txt', $input.':');
You can use a regular expression match to locate lines beginning with the given input:
$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
// Found input
var_dump($match[1]);
}
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) ;
}
}
$file = file_get_contents("http://www.bigsite.com");
How could i go about removing all lines from string $file that contains the word "hello" ?
$file = file_get_contents("http://www.bigsite.com");
$lines = explode("\n", $file);
$exclude = array();
foreach ($lines as $line) {
if (strpos($line, 'hello') !== FALSE) {
continue;
}
$exclude[] = $line;
}
echo implode("\n", $exclude);
$file = file_get_contents("http://www.example.com");
// remove sigle word hello
echo preg_replace('/(hello)/im', '', $file);
// remove multiple words hello, foo, bar, foobar
echo preg_replace('/(hello|foo|bar|foobar)/im', '', $file);
EDIT Removing the Lines
// read each file lines in array
$lines = file('http://example.com/');
// match single word hello
$pattern = '/(hello)/im';
// match multiple words hello, foo, bar, foobar
$pattern = '/(hello|foo|bar|foobar)/im';
$rows = array();
foreach ($lines as $key => $value) {
if (!preg_match($pattern, $value)) {
// lines not containing hello
$rows[] = $line;
}
}
// now create the paragraph again
echo implode("\n", $rows);
Here you go:
$file = file('http://www.bigsite.com');
foreach( $file as $key=>$line ) {
if( false !== strpos($line, 'hello') ) {
unset $file[$key];
}
}
$file = implode("\n", $file);
$file = file_get_contents("http://www.bigsite.com");
echo preg_replace('/((^|\n).*hello.*(\n|$))/', "\n", $file).trim();
The 4 patterns are for matching
if the first line has hello
A center line has hello
The last line has hello
The only line has hello
In case this are files with \r\n (Carriage return & Newline like on Windows) you need to modify this accordingly. The Trim can remove trailing and/or leading newlines
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;
}
?>
I have a huge library file containing a word and it's synonyms, this is some words and their synonyms in the format of my library:
aantarrão|1
igrejeiro|igrejeiro|aantarrão|beato
aãsolar|1
desolar|desolar|aãsolar|afligir|arrasar|arruinar|consternar|despovoar|devastar|magoar
aba|11
amparo|amparo|aba|abrigo|achego|acostamento|adminículo|agasalho|ajuda|anteparo|apadrinhamento|apoio|arrimo|asilo|assistência|auxíjlio|auxílio|baluarte|bordão|broquel|coluna|conchego|defesa|égide|encosto|escora|esteio|favor|fulcro|muro|patrocínio|proteção|proteçâo|resguardo|socorro|sustentáculo|tutela|tutoria
apoio|apoio|aba|adesão|adminículo|amparo|aprovação|arrimo|assentimento|base|bordão|coluna|conchego|descanso|eixo|encosto|escora|espeque|fé|fulcro|proteçâo|proteção|refúgio|socorro|sustentáculo
beira|beira|aba|beirada|borda|bordo|cairel|encosta|extremidade|falda|iminência|margem|orla|ourela|proximidade|rai|riba|sopé|vertente
beirada|beirada|aba|beira|encosta|falda|margem|sopé|vertente
encosta|encosta|aba|beira|beirada|clivo|falda|lomba|sopé|subida|vertente
falda|falda|aba|beira|beirada|encosta|fralda|sopé|vertente
fralda|fralda|aba|falda|raiss|raiz|sopé
prestígio|prestígio|aba|auréola|autoridade|domínio|força|halo|importância|influência|preponderância|valia|valimento|valor
proteção|proteção|aba|abrigo|agasalho|ajuda|amparo|apoio|arrimo|asilo|auspiciar|auxílio|bafejo|capa|custódia|defesa|égide|escora|fautoria|favor|fomento|garantia|paládio|patrocínio|pistolão|quartel|refúgio|socorro|tutela|tutoria
sopé|sopé|aba|base|beira|beirada|encosta|falda|fralda|raiz|vertente
vertente|vertente|aba|beira|beirada|declive|encosta|falda|sopé
see aantarrão is a word and below it are the synonyms, I can't think of a way to get the word and the synonyms on an associative array, this is what I'm trying to do:
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
}
?>
nothing, lol, what can I do here ? loop lines until I find an empty line then try to get a new word with the explode ?, help !
Here's some code I cooked up that seems to work.
See the code in action here: http://codepad.org/TVpYgW91
See the code here
UPDATED to read line by line
<?php
$filepointer = fopen("library.txt", "rb");
$words = array();
while(!feof($filepointer)) {
$line = trim(fgets($filepointer));
$content = explode("|", $line);
if (count($content) == 0)
continue;
if (is_numeric(end($content))) {
$word = reset($content);
continue;
}
if (isset($words[$word]))
$words[$word] = array_merge($words[$word], $content);
else
$words[$word] = $content;
}
print_r($words);
So what's the strategy?
fix up the line endings
run through the file line by line
ignore empty lines (count($content))
split the line up on the pipes, if the line has a numerical value for the last value, then this becomes our word
we only get to the last step if none of the other traps got touched, because of the continue statements, so if it is then just split up the words by the pipe and add them to or create the array element.
Try this. I can't remember if array_merge() will work with a null, but the basic idea is that $word is the $key to the assoc array.
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
else if(!empty($explode))
{
$array_sinonimos[$word] = array_merge($synonyms[$word], $explode);
}
}
?>