php remove the space in the beginning - php

I am having an array in PHP which contains some line breaks (\n) also as the array elements. I am writing these array elements into the CSV file using fwrite statement as below.
$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line);
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);
ltrim is not working as it trims only leading white spaces. I have to replace the extra space in the beginning of the CSV file while it is getting written.
The CSV file is getting written as below.
Jack 1234
John 3456
Jason 3321
I am expecting to write into the CSV file as below.
Jack 1234
John 3456
Jason 3321

$newLine[] = $row[$i].",";
$newLine[] = "\n";
$csv2 [] = implode(" ", $newLine);
$file1 = fopen("/home/huadong/public_html/ramesh/output_updated.csv","w");
foreach ($csv2 as $line):
$line1 = ltrim($line," ");
fwrite($file1, $line1 . PHP_EOL);
endforeach;
fclose($file1);

You can use PHP's substr() function and a while loop, like this:
$name=" Jack 1234";
while(substr($name,0,1)==" ") $name=substr($name,1);
echo $name;//Jack 1234

Just change
$line1 = ltrim($line);
to this
$line1 = ltrim($line," ");

Related

Split line by line text file

I have this kind of text file.
"u901_humext ""2019-02-01 23:24"" 99.74 99.9 99.82".
And I want to read line one by one and put into a variable like:
name = u901_humext
date = 2019-02-01 23:24
min = 99.74
But I don't know how to split it.
You can do this as below:
$string = '"u901_humext ""2019-02-01 23:24"" 99.74 99.9 99.82"';
$explodedArray = explode('"', $string);
foreach($explodedArray as $key => $element){
$explodedArray[$key] = trim($element, ' "');
}
echo "Name: ".$explodedArray[0]."\n";
echo "Date: ".$explodedArray[1]."\n";
echo "Min: ".$explodedArray[2];
Explanation:
Firstly split the string using explode() function of PHP.
Then loop through each element of the array. Trim each element of the array to remove "(double quote) and (space).
Print the elements

Deleting spaces from a string

I have a form where people enter their multiple codes.
Now, I would like to delete the spaces between these codes.
However, my code doesnt seem to work. Any ideas?
$codes = $_GET['codes'];
$spaces = strpos($codes, " ");
for($spaces; $spaces=0; $spaces--){
str_replace(" ", "", $codes);
echo $codes;
}
EDIT: I just have tried something else but it still doesnt work at all. I mean the echo gives me the original string every single time.
$codes = $_GET['codes'];
$cleancodes = str_replace(" ", "", $codes);
$cleancodes = trim(preg_replace('/\s\s+/', ' ', $cleancodes));
echo "<br / >" . $cleancodes;
$string = str_replace(' ', '', $string);
$text=str_replace(" ","",$text);
But doing that for code? Bound to break (if you meant program code)!
Use str_replace():-
<?php
$_GET['codes'] = "abc def ghi jkl mno pqr stu vwx yz ";
$codes = $_GET['codes'];
$codes = str_replace(" ","",$codes);
echo $codes;
Output:-https://eval.in/395364

Add comma to the end of every line in a text file PHP

I started learning PHP this week and need to add a comma to the end of every line in a text file. I don't really know where to start. What would I do after I load the file? I can't find any tutorial saying how to write to the end of every line only the beginning of the file or end?? Is it possible to specify the end of a every line?
What I have so far:
fopen("file.txt",a)
????
I'm using "a" because I want to preserve the data.
This should work for you:
(Here I just get all file lines with file(). Then I go through each line with array_map() and concatenate a comma at the end. After this I save the file with the new content with file_put_contents())
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map(function($v){return $v . "," . PHP_EOL;}, $lines);
file_put_contents("test.txt", $lines);
?>
Example file:
a
a
a
after the script:
a,
a,
a,
EDIT:
If you don't want to add a comma to an empty line just add a condition to check if the line is empty or not like this:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map(function($v){return $v . (empty($v)?"":",") . PHP_EOL;}, $lines);
file_put_contents("test.txt", $lines);
?>
Do you want to replace all the EOL with some specific character ?
$EOLChar=",";
$myFile = fopen("file.txt", "r") ;
$newFile="";
while(!feof($myFile)) {
$newFile.= str_replace(PHP_EOL, $EOLChar, fgets($myFile));
}
fclose($myFile);
file_put_contents("file.txt", $newFile);

Using tabs spacing in php for text file

I'm reading a CSV file and printing the data from the CSV file to 2 .txt files. The output of the text files are as follows
John
Georgina,Sinclair,408999703657,cheque,"First National Bank",Fourways,275.00,12/01/2012
Toby,Henderson,401255489873,cheque,"First National Bank",Edenvale,181.03,12/13/2012
Here is my code:
$file_handle = fopen("debitorders.csv", "r") or die("can't open debitorders.csv");
$absaFile = fopen("ABSA.txt", "w") or die("can't open ABSA.txt");
$firstNationalBankFile = fopen("First National Bank.txt", "w") or die("can't open First National Bank.txt");
while (!feof($file_handle) ) {
$debitorders = fgetcsv($file_handle, 1024, ",");
if ($debitorders[4] == "ABSA"){
print_r ($debitorders[4] . "<br />");
fputcsv($absaFile, $debitorders);
$ABSA_bank = "ABSA";
fopen("ABSA.txt", "a");
file_put_contents('ABSA.txt', $ABSA_bank, FILE_APPEND);
}
if ($debitorders[4] == "First National Bank"){
$FNB_bank = "First National Bank";
print_r ($debitorders[4] . "<br />");
fputcsv($firstNationalBankFile, $debitorders);
$FNB_bank = "First National Bank";
fopen("First National Bank.txt", "a");
file_put_contents('First National Bank.txt', $FNB_bank, FILE_APPEND);
}
}
fclose($file_handle);
fclose($absaFile);
fclose($firstNationalBankFile);
How can I put tab spaces in the output file instead of commas, so that the output instead looks like this:
John
GeorginaSinclair 408999703657 cheque First National Bank Fourways 275.0012/01/2012
TobyHenderson 401255489873 cheque First National Bank Edenvale 181.0312/13/2012
Any help would be appreciated. Thank You
I did something similar a while back although it was the other way around. I replaced tabs with commas. Here is the code I used:
preg_replace('/[ ]{2,}|[\t]/', ',', $string);
The code above removed two tabs and replaced with one comma. So maybe try it this way:
preg_replace(',', '/[ ]{1,}|[\t]/', $string);
As per php manual
int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
So you can try
fputcsv($absaFile, $debitorders ,"\t");

highlight multiple word from file on php?

I got a file filter.txt with words that I want to highlight on a string.
Filter.txt:
test1
test2
My solution doesen't work:
<?php
$file = file_get_contents('/home/user/filter.txt', true);
$keyword=$file;
$str="This is a test1 and test2 and test3";
$keyword = implode('|',explode(' ',preg_quote($keyword)));
$str = preg_replace("/($keyword)/i","<b>$0</b>",$str);
echo $str;
?>
Anyone?
took me like 15 mins but I eventually got it :)
<?php
$file = file_get_contents('/home/user/filter.txt', true);
$keywords = $file;
$str = "This is a test1 and test2 and test3";
$keywords = explode(" ", $keywords);
$str = preg_replace('/'.implode('|', $keywords).'/', '<b>$0</b>', $str);
echo $str;
?>
and this is expecting your filter.txt to be laid out like test1 test2 test3 etc. I'd suggest separating by new line or a pipe, |
try trimming the contents you might be getting a whitespace after the second keyword
$keyword=trim( file_get_contents("filter.txt",true) );

Categories