Are in_array() and file() compatible in php? - php

In the same location of my php file there's a "namestable.txt" file, full of names:
John
Alex
Tim
I have the following variable
$names = file("/names table.txt");
I tried to use the in_array with $names, but it doesn't work:
in_array($names)
I tested $names and I can echo all the values, so it behaves as a regular array.
I also created an array inside my php file and tested the in_array(), and it works with the PHP array. So, are file() and in_array() incompatible or I'm doing something wrong?

Your problem most likely is, that each line in namestable.txt ends with a newline (or carriage return and newline) character. So the array returned from file contains "John\n", "Alex\n" and "Tim\n".
If you pass the FILE_IGNORE_NEW_LINES to file, it will strip the newlines for you.
$names = file('namestable.txt', FILE_IGNORE_NEW_LINES);

Related

PHP Shuffle Text File and Rewrite Using File_Put_Contents

I've been trying for two days to create an array from a text file list, shuffle it, then rewrite the text file using file_put_contents.
I've succeeded in doing so BUT when I run the script more than once it creates multiple and random spaces between each item.
I've tried many different ideas but no joy yet.
Below is my code.
<?php
// create array from text file
$array = file('list.txt');
// shuffle the array
shuffle ($array);
// overwrite original with new shuffled text file
file_put_contents('list.txt', implode(PHP_EOL, $array));
?>
It seem like you may have extra line returns. These would also be part of the array and subject to random shuffling. IF you want to remove them you can do this
$array = array_filter(array_map('trim', $array));
The array map trim just runs trim() on every item in the array, this will help get rid of lines that have spaces in them instead of being strictly empty. Trim simply removes any whitespace from the front and back of a string, in the case that the whole line is whitespace then all the whitespace is removed leaving an empty string '' for that line.
The array filter will remove any lines that evaluate out to 0 in php this is '' 0 false null and maybe a few other things.
So by combining them we can easily filter out any lines that contain only whitespace or are empty.

Remove lines with specific pattern at the beginning of them

I have a text file of approximately 25,000 lines. About 525kb.
Some lines have random text at the beginning.
Some have long strings of semicolons.
Some others only have three semi-colons and then a space and optionally more text on the same line. These are the lines I want to remove.
Here is a sample....
;;; Updated Time 20120706122706
;;; Generic DEveloper Output
;;; Some Random Comments
;;; I got some more...
;;; Yet another uneeded line
;;; Thanks for using StackOverflow <http://stackoverflow.com>, or...
;;; Not.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Banana Production
[Data_Release_Version]
Version=12586
Released=20120706122706
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Baseline Properties
[BaseLineProperties]
Comment=BaselineProperties
----- and so on.
Once it gets to the first line with 4 or more ; on the line, I need the rest of the file as there are no ";;; " lines.
Trying to find something fast instead of reading everything line and writing it back out if it doesn't match ";;; ".
File is ASCII (possibly UTF-8) text type file.
Any ideas?
Thank you for your time, assistance and knowledge.
What I would suggest is to use file_get_contents() and save file's contents in a variable as a string, then use explode() that string at every newline character, then in a foreach loop, use preg_match() to check if the line begins with 3 semicolons and a space, if it dosent, put it in another array named $output. After foreach, implode() $output and add a newline character and use file_put_contents() to print it in another file. Hope this helps :-)
code:
<?php
$string = file_get_contents($filename);
$array = explode("\n",$string);
foreach($array as $arr) {
if(!(preg_match("^;;;\s",$arr))) {
$output[] = $arr;
}
}
$out = implode("\n",$output);
file_put_contents($path,$out);
?>
Depends.. I would try to load into a string, then do a explode() with newline, so it's in array, then run a foreach with a skip on any that doesnt have strpos == 0 -AND- strpos !== false, you can put in a continue to skip to the next line if it doesnt match.
Another option, is to parse, and skip, or even using fseek, and such. Depends on alot of different factors to determine whats going to be fastest.
You can implode later on, and add the newlines back in, and then push out a file, and/or use line breaks. Depending where the output is supposed to go.
I think you gave the answer yourself:
Make a script that reads the input file line by line in a loop (while). It writes every line into an output file if two conditions are met: 1. a flag ("done") is FALSE and 2. the line does NOT start with ";;; " (not the blank). This removes those lines starting with three semicolons. Once you come about a line containing more semicolons you set the flag to TRUE, thus the remaining lines wil be copied without being examined.

How can I replace empty space from shell_exec return?

I'm using php function shell_exec with the ls command:
shell_exec('ls');
The return is:
index.php index.php~ ajaxF.php ajaxF.php~ ajaxL.php ajaxL.php~ ajax.php
I noticed a space between every file and I tried to change it but it fail ('A' it's just a random character, in fact I want to add some html):
preg_replace('/ /', "A", $output);
preg_replace('/<br>/', "A", $output);
preg_replace('/\n/', "A", $output);
How can I replace this empty space by any other character?
The meaning of this is to add html data for every line.
Is it possible to split every line in an array?
By the way, I'm using ubuntu.
Thanks!
Why not use glob('*'), which'll return an array of files in the current directory? Then you can use implode() and insert any separator char/text you want.
ref: http://php.net/glob http://php.net/implode

Use line-break as separator for an array input?

I've never actually used arrays before, as I've never had to so far (a simple variable has been enough for me), however now I've created a form with a text-area that is meant to POST multiple urls through to my PHP script.
What I want to do is use a line-break in the visitors input to act as a separator for an array input.
For example, the visitor inputs 90 lines of text (all url's), the array breaks each one into a list of 90, and creates an array value for each one.
Any info, advice or comments would be greatly appreciated :)!
Not 100% percent sure what line breaks are used, e.g.:
Windows uses \r\n
Linux uses \n
(old) Macs used \r
However if you know this you can simply do:
$urls = explode("\n", $_POST['urls']);
EDIT
Actually after testing using regex IS faster than first doing a str_replace() and explode.
Look at http://www.php.net/manual/en/function.preg-split.php and as delimiter use new line sign
or see PHP REGEX - text to array by preg_split at line break
be careful about using just \r or \n because every operating system has "new line" defined another way
see answer by Tgr on SO question PHP REGEX - text to array by preg_split at line break
Use explode
$array=explode("\n",$_POST['textarea']);

Should I use \r or \n for explode()ing the contents of a file in PHP?

I'm creating a function which can accept a string which is either retrieved through file_get_contents() on a local text file, or something fetched from a url such as http://site.com/338383.txt.
The file will be a tab seperated file, with each item in the file being on its own line. Is it better to use \n or \r to explode() the string and get an array of each line?
I've noticed that in some cases \n doesn't work. I'd like a consistent way which works all the time. Any thoughts?
You can use file() to get the contents of the file as array with individual lines.
As duckyflip points out, you can use the file() function to get an array of file lines. However, if you still need to explode (for an unknown reason), you should use the PHP constant PHP_EOL instead of '\n' as this is cross-platform compliant.
Problem is that newline is defined differently for different "text/plain" encodings and platforms. The quick-and-dirty solution would probably be to use split and the regular expression "\r\n|\r|\n", however, it may break on some unicode files and it has no sense of "context". I.e. if you have a file where LF (\n) is used as a EOL marker, and there's some CRs there which should have been preserved, the CRs will be split on as well.
You can use preg_split () to explode by /\n\r|\n|\r/, and then trim () each item to make sure no trailing whitespace is remaining (if it’s appropriate).

Categories