Php and javascript array - skipping blank values and adding to new array? - php

I have an array in php that contains all the lines of a text files (each line being one value of the array). My text file had blank lines so the array has blank lines too. I wanted to search the array for a certain value like this:
$array = array();
$lines = file("textfile.txt"); //file in to an array
foreach ($lines as $line)
{
if (stripos($line, "$$") !== false)
{
$array[] = str_replace("$$", "", $line);
}
}
The code above is searching for a $$ and replacing it with a blank. The text file holds a line with a $$1 or any number and I want it to find all instances of that line, which it is doing.
My problem is that I want it to find the next 5 lines that aren't blank after finding the $$(number) and put them into a multi dimensional array. The multidimensional array looking similar to this (the program is a test in case you are wondering why the array is named the way it is):
$test = array(
array('question' => 'What is the answer', 'ansa' => "answera", 'ansb' => "answerb", 'ansc' => "answerc", 'ansd' => "answerd"), // $test[1]
array('question' => 'What is the answer', 'ansa' => "answera", 'ansb' => "answerb", 'ansc' => "answerc", 'ansd' => "answerd"), // $test[2]
);
The next five lines after the $$(number) are a question and four answers that need to go into the array. My code with regxp and searching isn't working so i discarded it.

you can try something like this...
<?php
$lines = array_filter(file('text.txt')); //file in to an array
$questions = array();
// find your starts and pull out questions
foreach ($lines as $k=>$line)
{
if (stripos($line, "$$") !== false)
{
$questions[] = array_slice($lines, $k, 5);
}
}
// dump
var_dump($questions);
See php manual for array_slice

Have you looked at preg_replace_callback?
Something along these lines should work:
<?php
function replace_callback($matches) {
var_dump($matches);
}
preg_replace_callback('/\$\$[0-9]+\s+([^'.PHP_EOL.']+){5}/is', 'replace_callback', file_get_contents('textfile.txt'));
?>

Related

If variable contains word, show it and get line number

So I trying to check "if text file on server contains word, show it and display his line number" but i only know how to check "if text file contains word". Anybody have sugesstions how to do it? I saw many tutorials but there are about local text files.
For now I have only this function
function readStrLine($str, $n) {
$lines = explode(PHP_EOL, $str);
return $lines[$n-1];
}
But I need line number.
For example I have text file saved on my server. examplesite.com/file.txt with
this content:
ABCDEF
123456
QWERTY
For now program reads content and checks if there is containing word. But I need the number of this line where this word is.
Example:
<?php
$desiredWord = 'apple';
$fileString = file_get_contents('asd.txt');
$lines = explode(PHP_EOL, $fileString);
$results = [];
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $desiredWord) !== false) {
$results[] = ($lineNumber + 1) .":{$line}";
}
}
foreach ($results as $result) {
echo '<pre>' . print_r($result, true) . '</pre>';
}
Input file content:
apple
asdfsdf
vs
werwerwer
llll
hhheeheh
there is an apple on the tree
the tree does not fall far from it's apple
Output:
1:apple
7:there is an apple on the tree
8:the tree does not fall far from it's apple
You can go through on the lines with a foreach. The $lineNumber key contains the line index you are currently reading, and the $line is the string of the current line. The explode function will index your array from 0, so first line index will be 0 when you read it. That's why the + 1 in this line: $results[] = ($lineNumber + 1) .":{$line}";
With the if (strpos($line, $desiredWord) !== false) you are checking if you find the desired word in the given line. If you want only one result you can return here, but if you would like to collect all of the lines where the word can be found, then you store the found lines like this in the $results
Finally you can check the findings with the second foreach, or any other way - depends on your implementation.

PHP Search and echo Array containing string

This appears to be a simple task, but none of the previous posts quite addresses the nuances of this particular problem. I appreciate your patience with a new programmer.
I want to divide a text file (comments.txt) into arrays with the tilde as a divider. Then I want to pass a user string variable (nam) to the PHP and search for this string. The result should echo every whole array that contains the string anywhere inside of it.
For example:
Array
(
[0] => hotdog
[1] => milk
[2] => dog catcher
)
A search for "dog" would produce on screen:
hotdog dog catcher
<?php
$search = $_POST['nam'];
$file = file_get_contents('comments.txt');
$split = explode("~", $file);
foreach ($split as $subarray)
{
if(in_array($search, $subarray))
{
echo $subarray;
}
}
?>
The simple task is now this embarrassing mess. If you are patient enough, could someone demonstrate the above code correctly? Thanks for your attention.
Assuming you have 'comments.txt' and it contains something like:
hamburger~hotdog~milk~dog catcher~cat~dogbone
then this should work
$comments = file_get_contents("comments.txt");
$array = explode("~",$comments);
$search = "dog";
$matches = array();
foreach($array as $item){ // check each comment in array
if(strstr($item, $search)){ // use strstr to check if $search is in $item
$matches[] = $item; // if it is, add it to the array $matches
}
}
var_dump($matches);
First, you might want to try using file() instead of file_get_contents(). This should do what you're looking for:
<?php
$search = $_POST['nam'];
$file = file('contents.txt');
$matches = array();
foreach ($file as $k => $v) {
if ($a = explode('~', $v)) {
foreach ($a as $possible_match) {
if (preg_match('"/'. $search .'"/i', $possible_match)) {
$matches[] = $possible_match;
}
}
}
print_r($matches);
?>
This method will allow you to maintain several different records (one in each line of the file) and interpret/process them independently.

multidimensional array processing

I have a tab delimited text file like this:
"abcdef1" "AB"
"abcdef1" "CD"
"ghijkl3" "AA"
"ghijkl3" "BB"
"ghijkl3" "CC"
For every common ID (e.g. abcdef1), I need to take the two digit code an concatenate it into a multi-value. So, eventually it should look like:
"abcdef1" "AB,CD"
"ghijk13", "AA,BB,CC"
I dont need to create a new output txt file but if i can get the final values in an array that would be great. I am just a week old to php, hence looking for help with this. I was able to get the values from the input txt file into an array, but further processing the array to get the common ID and take the 2 digit code and concatenate is something I'm struggling with. Any help is greatly appreciated
How about:
$values = array();
$handle = fopen($file, 'r');
// get the line as an array of fields
while (($row = fgetcsv($handle, 1000, "\t")) !== false) {
// we haven't seen this ID yet
if (!isset($values[$row[0]])) {
$values[$row[0]] = array();
}
// add the code to the ID's list of codes
$values[$row[0]][] = $row[1];
}
$values will be something like:
Array
(
[abcdef1] => Array
(
[0] => AB
[1] => CD
)
[ghijkl3] => Array
(
[0] => AA
[1] => BB
[2] => CC
)
)
There are a number of steps to the task you want to do. The first step, obviously, is getting the contents of your file. You state that you've already been able to get the contents of the file into an array. You may have done something like this:
// Assuming that $pathToFile has the correct path to your data file
$entireFile = file_get_contents( $pathToFile );
$lines = explode( '\n', $entireFile ); // Replace '\n' with '\r\n' if on Windows
How you get the lines into the array is less important. From here on out I assume that you've managed to fill the $lines array. Once you have this, the rest is fairly simple:
// Create an empty array to store the results in
$results = array();
foreach( $lines as $line ){
// Split the line apart at the tab character
$elements = explode( "\t", $line );
// Check to see if this ID has been seen
if( array_key_exists( $elements[0], $results ){
// If so, append this code to the existing codes for this ID (along with a comma)
$results[ $elements[0] ] .= ',' . $elements[1];
} else {
// If not, this is the first time we've seen this ID, start collecting codes
$results[ $elements[0] ] = $elements[1];
}
}
// Now $results has the array you are hoping for
There are some variations on this -- for example, if you want to get rid of the quote marks around each ID or around each code, you can replace $results[ $elements[0] ] with $results[ trim( $elements[0], '"' ) ] and/or replace $elements[1] with trim( $elements[1], '"' ).

php read product data txt file

I have a .txt file with product data, which I want to read in php. Each line contains one product, and the product details (number, name and price) are separated by tabs. As you can see below, it is not always true that the prices are nicely aligned vertically, because of the difference in length for the prodcut names. The data look like this:
ABC001 an item description $5.50
XYZ999 an other item $6
PPP000 yet another one $8.99
AKA010 one w a longer name $3.33
J_B007 a very long name, to show tabs $99
(I didn't know how to show the tabs, so they are spaces in the example above, but in the real file, it are real tabs)
What is the most efficient way to do this? (by the way, it is a remote file) I would love to have an array containing the product data per product:
$product['number'], $product['name'] and $product['price']
Thanks very much!
You could read the file line by line (using the function file, for instance, that will get you each line into one line of an array).
And, then, use explode on each of those lines, to separate the fields :
$data_of_line = explode("\t", $string_line);
Using "\t" (tabulation") as a separator.
You'd then have $data_of_line[0] containing the number, $data_of_line[1] the name, and $data_of_line[2] the price.
1) Easiest way is using file() to load all the lines into an array (unless the file is really big, then i would consider another approach).
2) split each line by tab ("\t" character)
3) "format" the array columns as you wish.
Sample snippet:
$productsArray = file($productsFileName, FILE_IGNORE_NEW_LINES);
foreach ($productsArray as $key => &$product) {
$arr = explode("\t", $product);
$product = array('number' => $arr[0], 'name' => $arr[1], 'price' => $arr[2]);
}
var_dump($productsArray);
fgetcsv() is a good function
check out the example from
http://us3.php.net/manual/en/function.fgetcsv.php, here's a slightly modified version:
$products = array();
$handle = fopen("products.txt", "r");
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$products[] = array(
'number' => $data[0],
'name' => $data[1],
'price' => $data[2]
);
}
fclose($handle);
$fileArr = file('path.to.your.file.txt');
$productsData = array();
for ($i = 0; $i < count($fileArr); $i++) {
$lineData = preg_match('/^(\w{3}\d{3})\s+(.*)\s+\$(\d+(\.\d+))$/', $fileArr[$i], $matches);
$productsData[] = array(
'number' => $matches[1],
'name' => $matches[2],
'price' => $matches[3]
);
}
This will be slower the using explode but it can also parse files that have more then just one tab as a separator between values. Plus you won't have to strip $ sign from the prices. If you wan't to keep $ sign with the price you should use this regex instead:
'/^(\w{3}\d{3})\s+(.*)\s+(\$\d+(\.\d+))$/'

php function to split an array at each blank line?

I'm building a script which will open a saved text file, export the contents to an array and then dump the contents in a database. So far I've been able to get the file upload working quite happily and can also open said file.
The trouble I'm having is the contents of the file are variable, they have a fixed structure but the contents will change every time. The structure of the file is that each "section" is seperated by a blank line.
I've used php's file() to get an array ... I'm not sure if there's a way to then split that array up every time it comes across a blank line?
$file = $target_path;
$data = file($file) or die('Could not read file!');
Example output:
[0] => domain.com
[1] => # Files to be checked
[2] => /www/06.php
[3] => /www/08.php
[4] =>
[5] => domain2.com
[6] => # Files to be checked
[7] => /cgi-bin/cache.txt
[8] => /cgi-bin/log.txt
[9] =>
[10] => domain3.com
[11] => # Files to be checked
[12] => /www/Content.js
[13] =>
I know that Field 0 and 1 will be constants, they will always be a domain name then that hash line. The lines thereafter could be anywhere between 1 line and 1000 lines.
I've looked at array_chunk() which is close to what I want but it works on a numerical value, what would be good if there was something which would work on a specified value (like a new line, or a comma or something of that sort!).
Lastly, apologies if this has been answered previously. I've searched the usual places a few times for potential solutions.
Hope you can help :)
Foxed
I think what you're looking for is preg_split. If you just split on a carriage return, you might miss lines that just have spaces or tabs.
$output = array(...);//what you just posted
$string_output = implode('', $output);
$array_with_only_populated_lines = preg_split('`\n\W+`', $string_output);
You could just do something like this. You could change it also to read the file in line-by-line rather than using file(), which would use less memory, which might be important if you use larger files.
$handle = fopen('blah', 'r');
$blocks = array();
$currentBlock = array();
while (!feof($handle)) {
$line = fgets($handle);
if (trim($line) == '') {
if ($currentBlock) {
$blocks[] = $currentBlock;
$currentBlock = array();
}
} else {
$currentBlock[] = $line;
}
}
fclose($handle);
//if is anything left
if ($currentBlock) {
$blocks[] = $currentBlock;
}
print_r($blocks);
Have you tried split('\n\n', $file);
?
You could do it by splitting first on the blank line and then on new lines, e.g.:
$file = $target_path;
$fileData = file_get_contents($file) or die('Could not read file!');
$parts = explode("\n\n", $data);
$data = array();
foreach ($parts as $part) {
$data[] = explode("\n", $part);
}
You could also use preg_split() in place of the first explode() with a regex to sp.lit on lines containing just whitespace (e.g. \s+)
I would use the function preg_grep() to reduce the resulting array:
$array = preg_grep('/[^\s]/', $array);

Categories