Make Php string without break lines - php

i need to generate random sentences from dictionary. In dictionary is every word at one line, firstly i load this dictionary to array and after it i have a for cycle and randomly pickup some data, but if i wrote it, so it is at one line in browser, but in source code is every word at another line. Then I need to create a set of XML files from search engine and this new lines are indexed as /n/r and in XML source code it has got a symbol 
 So my question is how i can make a sentence which will be at one line in source code too. Thanks.
Here is piece of my code i donĀ“t have here randomly loading data, i only made it for illustration in for cycle.
$file = fopen("test.txt", "r");
$data = array();
while (($buffer = fgets($file)) !== false) {
$data[] = $buffer;
}
$sentence = '';
for ($i=0;$i<10;$i++){
$sentence = $sentence . $data[$i];
}

Use trim function to filter new line characters.
In your code use:
$data[] = trim($buffer);

Related

Remove Line from String within txt file

Currently I have a code, which displays data from a txt file, and randomizes it after converting it into an array.
$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);
I am trying to make it so that, after this random value is displayed.
$search = $array[$rand_keys[0]];
We're able to store this into another txt file such as completed.txt and remove the randomized segment from our previous txt file. Here's the approach I tried, and surely didn't work out with.
$a = 'test.txt';
$b = file_get_contents('test.txt');
$c = str_replace($search, '', $b);
file_put_contents($a, $c);
Then to restore into a secondary file, I was messing with something like this.
$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $search;
}
}
file_put_contents('completed.txt', $result);
This actually appears to work to some extent, however when I look at the file completed.txt all of the contents are EXACTLY the same, and there's a bunch of blank spaces being left behind within test.txt
There are some better ways of doing it (IMHO), but at the moment you are just removing the actual line without the new line character. You may also find it will replace other lines as it just replaces the text without any idea of content.
But you will probably fix your code with the addition of replacing the new line...
$c = str_replace($search."\n", '', $b);
An alternative way of doing it is...
$fileName = 'test.txt';
$fileComplete = "completed.csv";
// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));
// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);

PHP: wrapping a string into a file object

quick question:
So I've written a bunch of crawling code, but one of the websites I'm crawling didn't include line breaks between tags. Since I've already written a bunch of code, I threw in a quick hack with preg_replace and continued from where I left off. Problem is, fopen() doesn't work on strings...
$string = file_get_contents($url);
$string = preg_replace("/>(^\n|\n+)?</", ">\n<", $string);
$file = fopen($string, 'r');
while(($buffer = fgets($file)) != false) { ... }
So, without rewriting my loop, how do I approach this?
Thanks for the help!
Rob
It seems you're looking to iterate over each line of the fetched page. You can do this after you've pulled it into a string by using the explode() function to break the string into an array at the line breaks:
foreach (explode("\n", $string) as $line) {
....
}

how to replace some part of text from the text file in php

I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).

In PHP, if I find a word in a file, can I make the line that the word came from into a $string

I want to find a word in a large list file.
Then, if and when that word is found, take the whole line of the list file that the word was found in?
so far I have not seen any PHP string functions to do this
Use a line-delimited regular expression to find the word, then your match will contain the whole line.
Something like:
preg_match('^.*WORD.*$, $filecontents, $matches);
Then $matches will have the full lines of the places it found WORD
You could use preg_match:
$arr = array();
preg_match("/^.*yourSearch.*$/", $fileContents, $arr);
$arr will then contain the matches.
$path = "/path/to/wordlist.txt";
$word = "Word";
$handle = fopen($path,'r');
$currentline = 1; //in case you want to know which line you got it from
while(!feof($handle))
{
$line = fgets($handle);
if(strpos($line,$word))
{
$lines[$currentline] = $line;
}
$currentline++;
}
fclose($handle);
If you want to only find a single line where the word occurs, then instead of saving it to an array, save it somewhere and just break after the match is made.
This should work quickly on files of any size (using file() on large files probably isn't good)
Try this one:
$searhString = "search";
$result = preg_grep("/^.*{$searhString}.*$/", file('/path/to/your/file.txt'));
print_r($result);
Explanation:
file() will read your file and produces array of lines
preg_grep() will return array element in which matching pattern is found
$result is the resulting array.

editing values stored in each subarray of an array

I am using the following code which lets me navigate to a particular array line, and subarray line and change its value.
What i need to do however, is change the first column of all rows to BLANK or NULL, or clear them out.
How can i change the code below to accomplish this?
<?php
$row = $_GET['row'];
$nfv = $_GET['value'];
$col = $_GET['col'];
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
$j = 0;
if (isset($csvpre[$row]))
{
$target_row = $csvpre[$row];
$info = explode("%%", $target_row);
if (isset($info[$col]))
{
$info[$col] = $nfv;
}
$csvpre[$row] = implode("%%", $info);
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
?>
Use foreach or array_map to perform the same action on all elements of an array.
In this case, something roughly along these lines?
foreach($rows as &$row) {
$row[0] = NULL;
}
I don't have a ready answer for you but I would recommend checking out CakePHP's Set class. It does things like this very well and (in some methods) supports XPath. Hopefully you can find the code you need there.
Depending on the size of that file, this could be much more efficient than looping through:
$data = file_get_contents("temp.php"); //data = blah%%blah%%blah%%blah%%###blah%%blah%%blah
$data = preg_replace( "/^(.+?)(?=%%)/", "\\1", $data ); //Replace first column to blank
$data = preg_replace( "/(###)(.+?)(?=%%))/", "\\1", $data ); //Replace all other columns to blank
After that, write it back to the file as you did above.
This would need to be adjusted to allow for escape characters if your columns allow %% to appear consecutively within them, but other than that, this should work.
If you expect this csv file to get REALLY large, you should start thinking of looping through the file line by line rather than reading it completely into memory using file_get_contents. I would point you to fgets_csv, but I don't believe it is possible to get each csv line by any delimiter other than newline (unless you are willing to replace your ### separator with \r\n). If you end up going this way, the answer totally changes :P
For more information on Regex (specifically positive lookaheads) see Regex Tutorial - Lookahead and Lookbehind Zero-Width Assertions (also a great site for regex in general)

Categories