PHP fwrite function new line - php

i have this code:
//This line is for the input that i've looped above my code, it's a URL
$textAr[$i] = str_replace("\r\n","", $textAr[$i]);
//This is for implode purposes
$finalArray = array($textAr[$i], $m1, $m2, $m3, $m4, $m5, $m6);
//When i echo this variable, $test, the URL is in the line along with the implode arrays
$test = implode($finalArray, "***");
echo $test."\n";
//This is for writing into my text file
fwrite($sitesTxt, implode($finalArray, "***")."\n");
I'm having the kind of error where after i input a 3 URLs, the first and second URL has new line after i write in the file, but the last URL I've input is in line along with the imploded arrays. I've even trimmed the $textArr, but i keep getting the new lines.
Expected output:
https://docs.google.com***false***false***false***false***false***false***
https://stackoverflow.com***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***
Output i'm getting at the txt file:
https://docs.google.com
***false***false***false***false***false***false***
https://stackoverflow.com
***false***false***false***false***false***false***
https://stackexchange.com***false***false***false***false***false***false***

Depending on your system, your lines may not end with a \r\n combination, but perhaps just \r.
I suggest either change str_replace to:
$textAr[$i] = str_replace(array("\r","\n"),"", $textAr[$i]);
Or, change the array:
$finalArray = array(trim($textAr[$i]), $m1, $m2, $m3, $m4, $m5, $m6);
Incidentally, although it will work, your implode parameters are reversed:
$test = implode("***", $finalArray);

You should use PHP_EOL constant for 'break-line' character. Because the break-line character in DOS is \r\n, but in *nix, it's just \n.
So, you replace the first line to
$textAr[$i] = str_replace(PHP_EOL, '', $textAr[$i]);

Related

How to remove lines containing a specific character (#) from file and echo out the data using PHP

I have a text file with data that looks like this:
#dacdcadcasvsa
#svsdvsd
#
#sfcnakjncfkajnc
I want to keep this line
and this one
How can I remove all lines containing # and echo out the lines that don't so it looks like:
I want to keep this line
and this one
All I know is that I have to get_file_contents($filename). Would I have to put it in an array?
Any tips and guidance would be appreciated.
Using file() and foreach()
$lines = file("a.txt");
foreach ( $lines as $line ) {
if ( $line[0] != '#' ){
echo $line;
}
}
Just update the name of the file.
You can replace all the comment lines with empty strings before you output.
<div style="white-space: pre-line;">
<?= preg_replace('/^#.*\n/m', '', file_get_contents($filename)) ?>
</div>
You're thinking along the right lines; although the PHP method (function) you need is actually file_get_contents(), not get_file_contents() (as per your question).
Let's break it down:
We need a way of separating out our data into sortable chunks. As you stated, the best way to do this is using an array.
We could do this, using the hash symbol (#) as a delimiter - but this
would mean the last chunk of text is a mixture of text we want to
remove, and text we want to keep. Instead, we'll be using line
breaks as our delimiter.
Once the data has been separated, we can work on removing those lines that begin with a hash symbol.
Our code will look something like this:
<?php
// Get the file contents
$fileContents = file_get_contents('my_file.txt'); // This could be any file extension
// Split the file by new lines
$contentsArr = preg_split('/\r\n|\r|\n/', $fileContents);
// Function for removing items from an array - https://stackoverflow.com/questions/9993168/remove-item-from-array-if-item-value-contains-searched-string-character?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
function myFilter($string) {
return strpos($string, '?') === false;
}
// Remove comment items from array
$newFileContents = array_filter($fileContents, 'myFilter');
// Concatenate and echo out the result
echo implode(",\n",$newFileContents);
An alternate because I was bored:
foreach(preg_grep('/^#/', file($filename), PREG_GREP_INVERT) as $line) {
echo $line;
}
Read file lines into an array
Get all lines NOT starting with ^ the # character
Loop those lines

Remove Next line at the beginning of a string in php

Im planning to remove all the Next line at the beginning of the string,
i tried using. str_replace("\n",null,$resultContent) it gives me the result that all Next line are removed.
Example. i need to remove the next line at the beginning of this string
"
String here
String following."
I need to delete the next line at the beginning
Please refer this page .
http://www.w3schools.com/php/func_string_trim.asp
use ltrim($resultContent,"\n") to remove all new line chars from starting of string.
Just explode and take the first result
Do not forget to do some test : if !is_array() .....
$x = explode("\n", $resultContent);
$resultContent = $x[0];
You can also use it like this:
if(startsWith($resultContent, '\n')) { // true: if string starts with '\n'
str_replace("\n",null,$resultContent);
}
Not sure whether you just want to strip blank lines, or remove everything after the \n from the first instance of a word... went with the former so hopefully this is what you're after:
$string = "String first line
string second line";
$replaced = preg_replace('/[\r\n]+/', PHP_EOL, $string);
echo $replaced;
Returns:
String first line
string second line
sounds like ltrim() is what you're looking for:
ltrim — Strip whitespace (or other characters) from the beginning of a
string!
echo $result_string = ltrim($string);

PHP replacing lines in a small paragraph from a big paragraph

I have 2 bulks of text: Trunk, and Card. Trunk has about 100 lines, and Card has 3. The 3 lines in Card exist in Trunk, but they aren't directly below eachother.
What I'm trying to do is remove each line of Card from the string Trunk.
What came to mind is exploding Card into an Array and using a for each in loop, like in AS3, but that didn't work like planned. Here's my attempt:
$zarray = explode("\n", $card); //Exploding the 3 lines which were seperated by linebreaks into an array
foreach ($zarray as $oneCard) //for each element of array
{
$oneCard.= "\n"; //add a linebreak at the end, so that when the text is removed from Trunk, there won't be an empty line in it.
print "$oneCard stuff"; //Strangely outputs all 3 elements of the array seperated by \r, instead of just 1, like this:
//card1\rcard2\rcard3 stuff
$zard = preg_replace("/$oneCard/i", "", $trunx, 1);//removes the line in Card from Trunk, case insensitive.
$trunx = $zard; //Trunk should now be one line shorter.
}
So, how can I use the foreach loop so that it replaces properly, and uses 1 element each time, instead of all of them in one go?
Consider
$trunk = "
a
b
c
d
e
f
";
$card = "
c
e
a
";
$newtrunk = implode("\n", array_diff(
explode("\n", $trunk),
explode("\n", $card)
));
print $newtrunk; // b d f
Or the other way round, your wording is a bit unclear.
Try this, it will be faster than the preg_replace due to the small amount being replaced:
//Find the new lines and add a delimiter
$card = str_replace("\n", "\n|#|", $card);
//Explode at the delimiter
$replaceParts = explode('|#|', $card);
//Perform the replacement with str_replace and use the array
$text = str_replace($replaceParts, '', $text);
This assumes there is always a newline after the search part and you do not care about case sensitivity.
If you do not know about the new line you will need a regex with an optional match for the newline.
If you need it case sensitive, look at str_ireplace
You could explode the $card, and keep the $trunk as string:
$needlearray = explode("\n", $card); //to generate the needle-array
$trunk = str_replace($needlearray,array(),$trunk); //replace the needle array by an empty array => replace by an empty string (according to the str_replace manual)
$trunk = str_replace("\n\n","\n",$trunk); //replace adjacent line breaks by only one line break

TextArea to Array with PHP

I'm trying to figure out how to convert html textarea into php array,
I've used a form with POST to deliver the query to the php script,
and the php file is getting them with the following line:
$ids = array($_POST['ids']);
Needless to say that it puts everything into one line
Array ( [0] => line1 line2 line3 line4 )
I need the final results to replace this:
$numbers = array(
"line1",
"line2",
"line3",
"line4"
);
What would be the best approach to divide and re-parse it ?
Using an explode on \n is a proper way to get new lines. keep in mind though that on some platforms the end of line is actually send by \r\n, so just exploding on \n could leave you with extra data on the end of each line.
My suggestion would be to remove the \r before exploding, so you dont have to loop through the entire array to trim the result. As a last improvement, you dont know that there actually is a $_POST['ids'], so always check it first.
<?
$input = isset($_POST['ids'])?$_POST['ids']:"";
//I dont check for empty() incase your app allows a 0 as ID.
if (strlen($input)==0) {
echo 'no input';
exit;
}
$ids = explode("\n", str_replace("\r", "", $input));
?>
I would've done the explode by Hugo like this:
$ids = explode(PHP_EOL, $input);
manual Predefined Constants
Just my two cents...
Use this
$new_array = array_values(array_filter(explode(PHP_EOL, $input)));
explode -> convert textarea to php array (that lines split by new line)
array_filter -> remove empty lines from array
array_values -> reset keys of array
If the textarea simply has line breaks per entry then I'd do something like:
$ids = nl2br($_POST['ids');
$ids = explode('<br />',$ids); //or just '<br>' depending on what nl2br uses.
Try with explode function:
$ids = $_POST['ids']; // not array($_POST['ids'])
$ids = explode(" ", $ids);
The first parameter is the delimiter which could be space, new line character \r\n, comma, colon etc. according to your string from the textarea (it's not clear from the question whether values are separated by spaces or by new lines).

Remove new lines from data retrived from text file using PHP

I have following data in text file
375020222511963
284970411563422
290245594366931
I need to retrieve a random variable from the above text file.
I use the following php code to do that
<?php
$file = file("file.txt");
$len = count($file);
$rand = rand ( 0, $len-1 );
echo $file[$rand];
?>
But it's returning new line along with the retrieved data. I need to retrieve data without new line.
The file() function has an optional second argument taking a bit mask of flags which affect what is returned in the array.
Available flags are FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES, and SKIP_EMPTY_LINES. The FILE_IGNORE_NEW_LINES is the one that you want to use in order to have each line in the array not include the trailing newline character.
So, your line of code should look like the following.
$file = file("file.txt", FILE_IGNORE_NEW_LINES);
Descriptions and more info, see http://php.net/file.
Change last line to:
echo trim($file[$rand]);
trim() removes white-spaces (blanks, new lines, tabs) from the beginning and end of a string.
In order to avoid empty lines... If the last line is always the only empty one:
$rand = rand (0, $len - 2); // Instead of -1
Else, if you can have empty lines everywhere, replace the last two lines of code with:
do {
$rand = rand (0, $len - 1);
} while (trim($file[$rand]) == '');
echo $file[$rand];

Categories