HTML textarea alignment - php

Suppose I have textarea filled with following text
employee/company/salary
john/microsoft/12.000
michael/citrusdata/15.000
How can I align each column vertically so I get following text:
employee__________company__________salary
john______________microsoft__________12.000
michael___________citrusdata__________15.000
In this example I used underscores to specify whitespaces, thought to write a simple function like nl2br() to replace '/' with one or many tab characters but it wont be a consistent solution, guess I need to read text line by line and considering the length of every word, I need to replace '/' with enough whitespace but dont have any idea how to code it, is there any other way?

I suppose you will output the textarea content outside the textarea itself, else you will need to use js alternative. My answer uses php :)
So, you may use the sprintf function that allows left or right padding.
Just split your content to get an array of lines
$lines = explode("\n", $content);
Take care of a eventual empty last entry (if your content end with a \n)
Then
foreach($lines as $line) {
$items = explode("/", $line) ;
echo sprintf("%-15s%-15s%-15s", $items[0], $items[1], $items[2]) . "<br/>";
}
"%-15" tells to left-pad with 15 empty spaces.
It works on console, but you have to nl2br it before echoing in web pages !
This is sample, so you have to add error testing (lines with only one / for example).

You should specify the width of each column like 50 characters for each or any desired width. let say it $COLUMN_WIDTH = 100;
find length of the column value (string) than subtract it from fixed length like
$COUNT_SPACES_TO_INSERT = $COLUMN_WIDTH - strlen($COLUMN_STR);
Than insert $COUNT_SPACES_TO_INSERT number of spaces it will solve your issue.

Related

PHP How to output a string that comes after a certain keyword in a long text

Basically, I want to take a long text file (source code), find a specific keyword in that file, and then print out the next 400 characters that come after that keyword. I don't want every thing after the keyword because that ends up being 20,000+ characters.
If I could, I'd like to delimit them right there (which is what I tried to do originally but failed) It's becoming very confusing very quickly. If I can just get the 400 characters, then I can save that to a text file, and then delimit that 400 character text file.
My code now is:
<?php
$website = $_GET["website"]; //I'm pulling the website from a form
$contents = file_get_contents($website));
$del = 'keyword';
$search = preg_quote($del, '/');
$search = "/^.*$search.*\$/m";
if(preg_match_all($search, $contents, $found)){
echo implode("\n", $found[0]);
}else{}
?>
The problem is the above prints out EVERYthing after the keyword, and I can't even take what I get and delimit it further. I'm at the point where the more I come up with ideas the further I'm getting from the solution.
Any help is greatly appreciated.
You can use substr($your_string, 0, 400) to get only 400 characters starting from string.
Syntax for using this method is substr(string,start,length)
You can do this with a combination of strpos, strlen and substr. You don't need any regex to do this, and you should not use it because regex generally is slow as death. Avoid regex whenever possible, and only use it when you don't have any other answer.
<?php
$website = $_GET["website"]; //I'm pulling the website from a form
$contents = file_get_contents($website));
$del = 'keyword';
//get the index of the end of your split value
//this is the character index of your keyword, plus the length of the keyword,
//so it will start collecting the next bit at the end of the first occurance of keyword.
$index = strpos($contents, $del) + strlen($del);
//get the text you want
$text = substr($contents, $index, 400);

create textbox in php

Is there any way to create a textbox of predefined width and height in php memory and store the text in it with word-wrapping, then return it line by line and store in array of variable.
I am actually trying to implement something similar to imagettfbbox but instead of returning dimensions, I want to return text in it line by line; so I could know that on which line and what place particular text or sentence would be after transforming into image.
Please share your ideas.
You might use chunk_split() to wrap a long string and then 'explode' the string to an array, like this:
$mylongstring = 'a very long text etc';
// Place a 'newline' character every 50 characters
$mylongwrappedstring = chunk_split($mylongstring, 50);
// Split the lines to an array
$lineArray = explode("\n", $mylongwrappedstring);
http://php.net/manual/en/function.chunk-split.php
I'll leave the image-processing/generation to you :)

Html2pdf doesn't support word-break:break-all css

hai everybody i am using html2pdf ,it doesn't support word-break:break-all css any idea?
example
<td style="width:30%;word-break:break-all ;">
testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets
</td>
output pdf take above 30% width like string length size
output pdf: testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets
I want Output :
testtestetstetstetstetstettstets tetstetstetstetstetstetstetstets
Well, that's complicated. Your teststring is too long, but it's not composed of multiple words. That means that word-break won't work, because there aren't any words to break on. Obviously, this might well just be an example, in which case it might be that html2pdf just doesn't support relative widths and word-break, so you could try having an absolute width and word-break.
That said, here's something I know that will work: wordwrap in PHP. So, instead of echo $yourvar; you could use echo wordwrap($yourvar, 75, "\n", true) instead, which will always cut the string, even if it's just one long string. It takes a little fiddling to get the number of characters to match up with the width that you're looking for, but it will work.
<?php
$foo = str_repeat('test',12);
echo wordwrap($foo, 20, '<br />', true);
Output:
testtesttesttesttest
testtesttesttesttest
testtest
try this;
<td style="width:30%; word-wrap:break-word;">
testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets
</td>
not word-break it is word-wrap ;
If you want long strings to wrap consistently within a boundary container I think you should be able to accomplish this by inserting zero-width space characters (​ or \xe2\x80\x8b) between every letter of the orignial string. This will have the effect of wrapping as if every character was its own word, but without displaying the spaces to the end user. This may cause you trouble with text searches or indexing on the final product, but it should accomplish the task reliably from an aesthetic perspective.
Thus:
testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets
Becomes
t​e​s​t​t​e​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s
(which displays: "t​e​s​t​t​e​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s​t​e​t​s")
So if you wrap it it will wrap exactly to the bounds of its container. Here's a fiddle of it as an example.
Just write a PHP script to loop though the string and insert the space:
$string="testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets";
$new_string = "";
for($i=0;$i<strlen($string);$i++){
if ($string[$i]==' ' || $string[$i+1]==' '){ //if it is a space or the next letter is a space, there's no reason to add a break character
continue;
}
$new_string .= $string[$i]."​";
}
echo $new_string
This is a particularly nice solution, because unlike wordwrap(), it automatically adjusts for non-fixed-width fonts (which is basically 99% of fonts that are actually used).
Again, if you need to resulting PDF to be searchable, this is not a good approach, but it will make it look like you want it to.
In your testing the word break will not work because the word break only works between the words in a particular sentence. So yo can use the multiple word sentence and then try with the word breaker
You just use substr function in your code.
I put a example for this. First put your output in variable.
$get_value = "testtestetstetstetstetstettstetstetstet";
$first = substr("$get_value",0,3);
$second = substr("$get_value",4,7);
and so on.
You can use "\r\n" to print newline character. make sure to use it with double quote. If your string is in the variable then you need to use word count function and append this string. You can also use PHP_EOL to avoid platform dependency.
html2pdf does not support this word-break:break-all css
Ref: http://www.yaronet.com/en/posts.php?sl=&h=0&s=151321#0
You may use this method.
<?php
$get_value = "testtestetstetstetstetstettstetstetstet";
$first = substr("$get_value",0,3);
$second = substr("$get_value",4,7);
$third = substr("$get_value",8,11);
?>
I want to add little bit of own experience with HTML2PDF and tables.
I used this solution to generate the PDF containing a table filled with delivery confirmation (list of products). Such list may contain up to thousand of products (rows).
I encountered a problem with formatting and long strings in cells. First problem was that the table was getting too wide even if I set the table's width to 100% and the width of header (<th>) columns (HTML2PDF does not support <colgroup> so I couldn't define it globally) - some columns were out of visible area. I used wordwrap() with <br /> as separator to break down the long strings which looked like it's working. Unfortunately, it turned out that if there is such long string in first and last row the whole table is prepended and appended with empty page. Not a real bugger but doesn't look nice either. The final solution was to (applies for tables which width could outreach the visible area):
set the fixed widths of table and each row in pixels
for A4 letter size I am using total width of 550 px with default margins but you'd have to play around a little to distribute the width between columns
in wordwrap use empty space or ​ / \xe2\x80\x8b as delimiter
For small tables that you'd like to spread for 100% of visible area width it is OK to use width expressed in %.
I think this function is a limping solution.
function String2PDFString($string,$Length)
{
$Arry=explode(" ",$string);
foreach($Arry as $Line)
{
if(strlen($Line)>$Length)
$NewString.=wordwrap ($Line,$Length," ",true);
else
$NewString.=" ".$Line;
}
return $NewString;
}

PHP Insert Multiple Spaces

I've got some data that needs to be cleaned up into a fixed length format. I'm using PHP to grab the data out, covert it, and put it back in, but it's not working as planned. There is a certain point in each piece in the middle of the data where there should be spaces to increase the length to the proper amount of characters. The code I'm using to do this is:
while ($row = mysql_fetch_array($databasetable)) {
$key = $row['KEY'];
$strlength = strlen($key);
while ($strlength < 33) {
$array = explode(' TA',$key);
$key = $array[0] . ' TA' . $array[1];
$strlength++;
}
}
It's taking a ' TA' and adding two spaces before it, rinse and repeat until the total length is 33, however when I output the value, it just returns a single space. Funny part is that even though it is displaying a single space, it returns a strlen of 33 even if it's not displaying 33 characters.
Any help in figuring this out would be greatly appreciated.
HTML will have extra spaces filtered out.
To force extra spaces to be shown, use ' ' rather than ' '.
#TVK- is correct, HTML ignores multiple-space whitespace - it'll turn it into one space.
In addition to his solution, you can use the CSS instruction white-space: pre to preserve spaces.
Remember that, when doing an output to a webbrowser, it'll interpret it as HTML ; and, in HTML, several blank spaces are displayed as one.
A possibility would be to use the var_dump() function, especially if coupled with the Xdebug extension, to get a better idea of your data -- or to display it as text, sending a text-related content-type.
BTW : if you want to make sure a string contains a certain amount of characters, you'll probably want to take a look at str_pad()
Easiest options for you I think are
Wrap your output in <pre> tags
replace each space with
If you're rendering HTML, consecutive spaces will be ignored. If you want to force rendering of these, try using
Generally using multiple non breakable spaces one after another is a bad idea and might not bring a desired result unless you're using a monospaced font. If you want to move some piece of text to a certain position on your page, consider using margins
You can tell the browser that the text is preformatted
this text will be displayed as it is formatted
spaces should all appear.
new lines will also be apparent
Have you looked into str_pad? something like :
str_pad ( 'mystring' , 33 , ' TA' , STR_PAD_LEFT );
I thing you can use str_repeat
echo str_repeat(" ", 15);

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