How to remove first whitespace of a string - php

I am building a new version of a telephone configuration manager where I am sucking on a stupid problem. You see these telephone .cfg configurations are rely static. So in the old version I made it gave the configuration without a problem.
It looks like this:
## Configuration header
configuration_1="parram"
configuration_2="parram"
configuration_3="parram"
etc.
Now in the new version the configuration is given as this:
whitespace
## Configuration header
configuration_1="parram"
configuration_2="parram"
configuration_3="parram"
Note that white space is actually white space and that the phone does not take the configuration, because it wants to see the first line have the #header.
So I figured that the easy way to fix this is to just backspace the first white line but how. How can I tell PHP to delete the first line?
OK, look at this: image
The first to screenshots are from phpMyAdmin where you see that inside an textarea there is no white space, but when just echoing it out you suddenly see it. The strange thing is that when manually changing the configuration with phpMyAdmin it is removed somehow, but it has be done automatically.

If you have the contents as a string, just run ltrim.
It will strip away all the whitespaces from the starting of the string.
$str = ltrim($str);

That is how to remove only the first whitespace:
$s = ' Text';
$arr = str_split($s);
array_shift($arr);
$s = implode('', $arr);
die($s);

If you got this configuration in a string, as your title says, you can just trim the string.
$config = trim($config);

I would delete up to the first hash -
$contents = substr($contents, 0, strpos($contents, "#") - 1)

You can use the PHP function trim.

Put the following code on the first line of the file:
ob_start();
Put the following code just before you displaying the content:
ob_end_clean();

Related

Remove front and end white space from a string

I see this question has been asked a few times but I couldn't find an answer in php.
I have the following string.
$myString = "‍ LLC."
I run this trim($myString);
and I get this back "‍ LLC."
according to the trim documentation it should delete the white space in the front and the back? What am I missing?
I also tried htis trim($myString, " "); same results
The e2808d at the beginning of bin2hex() output is ZERO WIDTH JOINER character and the reason for trim() to not trim it. Try (PHP 7):
echo trim($myString, "\u{200d} \t\n\r\0\x0B");
I think this is happening because of the empty space is not really a real white space (tab) looks like a hidden character (â). i copy your variable and value code into an online PHP editor and i got this:

Simple regex seems to cause infinite loop in PHP

The following 2 lines are my code:
$rank_content = file_get_contents('https://www.championsofregnum.com/index.php?l=1&ref=gmg&sec=42&world=2');
$tmp_ = preg_replace("/.+width=.16.> /Uis", "", $rank_content, 1);
The second line above causes an infinite loop.
In contrary, the following alternatives DO work:
$tmp_ = preg_replace("/.+width=.16.> /Ui", "", $rank_content, 1);
$tmp_ = preg_replace("/[^§]+width=.16.> /Uis", "", $rank_content, 1);
But sadly, they do not give me what I want - both alternatives do not include line breaks within $rank_content.
Also, if I replaced the file_get_contents function with something like
$rank_content = "asdfas\nasdfasdfaswidth=m16m> teststring";
There are no problems either, although \n represents a line break, too, doesn’t it?!
So do I understand it right that RegEx has problems in noticing a String with line breaks in it?
How can I filter a substring of $rank_content (which has multiple lines in it) by removing some lines until something like "width="16" " appears? (Can be seen in the site's source code)
Replace the m modifier with the s modifier. m changes the behaviour of ^ and $, whereas s changes the behaviour of .
That said, you should not be parsing HTML with regex. Seriously. Bad things happen.
I give up on it: It seems the problem is the LENGTH of the haystack variable $rank_content. Its length is about 90,000, while the maximum allowed length for regex match() is about 30,000, so I guess it is the same for regex replace().
Solving this problem would surely be possible, if somebody is interested: Have a look into this link -> PHP preg_match_all limit
I myself am going to solve the problem using another method for reading the contents of a website like HTML Unit or maybe retrieving the site line after line.

str_replace not working with txt file PHP

str_replace doesn't seem to be working as we expect it to.
We have a text file and we're trying to remove part of the file.
while(!feof($bodyfile)) {
$content = #fgets($bodyfile);
$content = str_replace("MARGIN","",$content);
(Obviously fopen is used to open the file as 'r')
Strangely enough, finding and replacing M works? but not margin..
UPDATE:
fgets() function reads only 1 line at the time, and by putting that line in your $content variable, you're overwriting the replacement for previous line, and doing it over and over again.
Try with this:
$content = "";
while(!feof($bodyfile)) {
$line = #fgets($bodyfile);
$content .= str_replace("MARGIN","",$line);
So, what this code does is reading the line and assigning it to the $line variable, and then adding the replaced string to your $content variable.
By adding # sign in front of your functions, you're suppressing errors which that function gives.
Try to remove # from your #fgets and see if there's any error.
Try var_dump($content) or echo $content to see if file is loaded correctly.
Remember that str_replace() is case sensitive.
you could do:
$str=implode("",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
$str=str_replace('MARGIN','',$str);
//OR
//$str=str_ireplace('MARGIN','',$str); for case insensitivity
fwrite($fp,$str,strlen($str));
Just found out the file is a UTF-16 character encoding rather than UTF-8 for some obscure reason. Converted, now my method originally works!
Thanks to all for suggestions

why is php trim is not really remove all whitespace and line breaks?

I am grabbing input from a file with the following code
$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh), " \t\n\r"))));
i had also previously tried these while troubleshooting
$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh)))));
$jap= addslashes(strtolower(trim(fgets($fh), " \t\n\r")));
and if I echo $jap it looks fine, so later in the code, without any other alterations to $jap it is inserted into the DB, however i noticed a comparison test that checks if this jap is already in the DB returned false when i can plainly see that a seemingly exact same entry of jap is in the DB. So I copy the jap entry that was inserted right from phpmyadmin or from my site where the jap is displayed and paste into a notepad i notice that it paste like this... (this is an exact paste into the below quotes)
"
バスにのって、うみへ行きました"
and obviously i need, it without that white space and breaks or whatever it is.
so as far as I can tell the trim is not doing what it says it will do. or im missing something here. if so what is it?
UPDATE:
with regards to Jacks answer
the preg_replace did not help but here is what i did, i used the
bin2hex() to determine that the part that "is not the part i want" is
efbbbf
i did this by taking $jap into str replace and removing the japanese i am expecting to find, and what is left goes into the bin2hex. and the result was the above "efbbbf"
echo bin2hex(str_replace("どちらがあなたの本ですか","",$jap));
output of the above was efbbbf
but what is it? can i make a str_replace to remove this somehow?
The trim function doesn't know about Unicode white spaces. You could try this:
preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $str);
As taken from: Trim unicode whitespace in PHP 5.2
Otherwise, you can do a bin2hex() to find out what characters are being added at the front.
Update
Your file contains a UTF8 BOM; to remove it:
$f = fopen("file.txt", "r");
$s = fread($f, 3);
if ($s !== "\xef\xbb\xbf") {
// bom not found, rewind file
fseek($f, 0, SEEK_SET);
}
// continue reading here

file_put_contents, file_append and line breaks

I'm writing a PHP script that adds numbers into a text file. I want to have one number on every line, like this:
1
5
8
12
If I use file_put_contents($filename, $commentnumber, FILE_APPEND), the result looks like:
15812
If I add a line break like file_put_contents($filename, $commentnumber . "\n", FILE_APPEND), spaces are added after each number and one empty line at the end (underscore represents spaces):
1_
5_
8_
12_
_
_
How do I get that function to add the numbers the way I want, without spaces?
Did you tried with PHP EOL constant?
file_put_contents($filename, $commentnumber . PHP_EOL, FILE_APPEND)
--- Added ---
I just realize that my file editor does the same, but don't worrie, is just a ghost character that the editor places there to signal that there is a newline
You could try this
A file with EOL after the last number looks like:
1_
2_
3_
EOF
but a file without that last character looks like
1_
2_
3
EOF
where _ means a space character
You could try to parse the file contents using php to see what's inside
$lines = explode( PHP_EOL, file_get_contents($file));
foreach($lines as $line ) {
var_dump($line);
}
...tricky
pauls answer has the correct approach but he has a mistake.
what you need ist the following:
file_put_contents($filename, trim($commentnumber).PHP_EOL, FILE_APPEND);
the PHP_EOL constant makes sure to use the right line ending on mac, windows and unix systems
the trim function removes any newline or whitespace on both sides of the string.
converting to integer would be a huge mistake because
1. you might end up having zero, expecially because of white space or special characters (wherever they come from...)
2. ids dont necessarily need to be integers
Ohh Guys! Just Use
\r\n
insted of \n
There is nothing in the code you provided that would generate those spaces, unless $commentnumber already contains the space to begin with. If that is the case, simply use trim($commentnumber) instead.
There is also nothing in your code that would explain empty lines at the bottom of the file, unless $commentnumber can be an empty string. If that is the case, and you want it to output the number 0 instead, use intval($commentnumber).
Of course, you need only one of those two. If you want to preserve string-like content, use trim(); if you always want integers, use intval(), which already trims it automatically.
It is also possible that you accidentally wrote " \n" instead of "\n" in your actual code, but in the code you posted here it is correct.
annoyingregistration, what you have there is absolutely fine.
PHP_EOL and "\n" are exactly the same.
The code you provided theres nothing wrong with it so it must be the value of $commentnumber that has a space at the end of it. as stated, run your $commentnumber through the trim() function.
file_put_contents($filename, trim($commentnumber . "\n"), FILE_APPEND);
Good luck.
After reading your code and responses, I have come up with a theory...
Since I can't see that there's anything wrong with your code, how did you open and read the file? Did you actually open it in a text editor? Did you use a PHP script to do it? If so, open the file with a text editor and check that there are actually spaces at the end of each line. If there is actually is...well, ignore the rest of this answer, then. If not, just read on.
For instance, if you use something like this:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo $line."<br />";
Then you would always a whitespace at the end of the line because of the way file() work. Make sure each $line does not have a whitespace - such as a newline character - at the end.
Since HTML handles all whitespaces - spaces, tabs, newlines etc. - as spaces, if there is a whitespace at the end of $line, then those would appear as spaces in the HTML output.
Solution: use rtrim($line) to remove whitespaces at the end of the lines. Using the following code:
<?php
$lines = file($filename);
if($lines) // Error reading
die();
foreach($lines as $line)
echo rtrim($line)."<br />";
wouldn't have the same problems as the first example, and all spaces at the end of the lines would be gone.
its because each time you write to the file, the file is being finished, file_put_contents inserts an extra line break at the end

Categories