PHP Insert Multiple Spaces - php

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);

Related

PHP is automatically removing whitespace I want to keep

I have a string I want to process which looks like this:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Note how there are multiple spaces between characters. The number of spaces is important, and thus I don't want them to be discarded. When I read this line from a file using php, it prints the following:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Maintaining only a single space where there were several before. How can I stop PHP from doing this?
Ultimately I want to substring the entire thing into an array of individual characters but I need the array position to be preserved.
Thank you!
EDIT: Example of what I'm talking about:
Replace it with the html entity for a non breaking space to view it rendered in browser's html
<?php
$str = ' HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH';
$str = str_replace(' ',' ',$str);
echo $str;
If you're viewing it with a browser you could use HTML to keep the formatting intact. For instance:
echo '<pre> HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH</pre>';
See: http://www.w3schools.com/tags/tag_pre.asp
I think <code> might also work.

HTML textarea alignment

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.

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;
}

White spaces are lost when echoing under php

I've got the following issue with PHP and PostgreSQL.
In a table I added the following value, mark the spaces.
Things: 10 POLI
When I read this out with PHP it will become
Things 10 POLI
My simpified code (for an ideal world without errors) is:
$query = "SELECT stuff, thing, planets FROM 42 WHERE answer = '-'";
$result = pg_query($connection, $query);
$resultTable = pg_fetch_all($result);
Then with
echo "Things: $result[stuff]";
My question is, which step eliminates all the white spaces? And how to get these spaces back? I know that most people want to remove them, I want to keep them.
that is not a PHP issue, but a HTML issue, becauyse if you output with echo, you do in fact generate HTML code.
The HTML specification defines, that multiple consecutive spaces get rendered as only one space.
If you want to avoid this, wrap a <pre> tag around the string:
echo "<pre>Things: $result[stuff]</pre>";
That's because browser does not recognize more than one space, you can use this code to convert consective spaces to (space understood by browser)
$str = str_replace(' ', ' ', $origText);
Or alternatively wrap your text in <pre> tag if that suites your requirements as suggested in comments below.

Add space before a numbers in PHP

How can I add space before numbers in PHP, to get output like the following?
 9  
10
100
I'm using str_pad($k,3,'',STR_PAD_LEFT), but blank space is not working. And I don't want leading zeros, but I want blank spaces.
You may be looking for str_pad().
foreach (array(1,2,3,100,1000) as $number)
echo str_pad($number, 10, " ", STR_PAD_LEFT);
However, if you want to output this in HTML, the multiple spaces will be converted to one. In that case, use as the third parameter.
Also, if you use a font like Times or Arial, this will never produce perfectly exact results, because characters differ in width. For perfect results, you need to use a Monospace font like Courier.
Anyway, check #Mark Baker's answer first. Right aligning the data using CSS's text-align: right is the best solution in most cases.
If you're displaying the result in a web browser, then you should be aware that browsers have this nasty little tendency to convert multiple white spaces to a single space. To check if your code is working, use the browser's "view source" option and count the spaces in the actual source rather than the rendered display.
Then look at alternatives such as or right-aligning your values using CSS.
When printing the numbers:
printf("%5d\n", $number);
Replace the 5 with how many spaces width minimum you want.
Use the function str_pad for this purpose.
This is what you are looking for:
str_replace(" "," ",str_pad($number, 5,' ', STR_PAD_LEFT));
grml, look into my comment. I don't know why here the nbsp :) is gone

Categories