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
Related
my code is not working ? and i dont want to use str_replace , for there maybe more slashes than 3 to be replaced. how can i do the job using preg_replace?
my code here like this:
<?php
$str='<li>
<span class=\"highlight\">Color</span>
Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
$str=preg_replace("#\\+#","\\",$str);
echo $str;
There is merit in the other answers, but to me it looks like what you're actually trying to accomplish is something very different. In the php code \\\' is not three slashes followed by an apostrophe, it's one escaped slash followed by an escaped apostrophe, and in the rendered output, that's exactly what you see—a slash followed by an apostrophe (with no need to escape them in the rendered html). It's important to realize that the escape character is not actually part of the string; it's merely a way to help you represent a character that normally has very different meaning in within php—in this case, an apostrophe normally terminates a string literal. What looks like 4 characters in php is actually only 2 characters in the string.
If this is the extent of your code, there's no need for string manipulation or regular expressions. What you actually need is just this:
<?php
$str='<li>
<span class="highlight">Color</span>
Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
echo $str;
?>
Only one escape character is needed here for the apostrophe, and in the rendered HTML you will see no slashes at all.
Further Reading:
Escape sequences
The root of this problem is actually in how it was written into your database and likely to be caused by magic_quotes_gpc; this was used in older versions and a really bad idea.
The best fix
This requires a few steps:
Fix the script that puts the HTML inside your database by disabling magic_quotes_gpc.
Write a script that reads all existing database entries, applies stripslashes() and saves the changes.
Fix the presentation part (though, that may need no changes at all.
Alternative patch
Use stripslashes() before you present the HTML.
use this pattern
preg_replace('#\\+#', '\\', $text);
This replaces two or more \ symbols preceding an ' symbol with \'
$theConvertedString = preg_replace("/\\{2,}'/", "\'", $theSourceString);
Ideally, you shouldn't have code causing this issue in the first place so I would have a look at why you have \\' in your code to begin with. If you've manually put it in your variables, take it out. Often, this also happens with multiple calls to addslashes() or mysql_real_escape_string() or a cheap hosting providers' automatic transformation of all POST request variables to escape slashes, combined with your server side PHP code to do the same.
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
testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets
(which displays: "testtestetstetstetstetstettstetstetstetstetstetstetstetstetstetstets")
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;
}
The following code outputs a b:
$var="a b"; // I inserted 3 white spaces, and HTML is rendering only one
echo $var;
The issue is that if I store $var in a table, it will KEEP the white spaces, and while reading, it strips them back. The striped data gets as it is updated in another table, resulting in mismatch of same values in both the tables.
I tried google search and found in a thread that its how HTML behaves. Any hope on how can I fix this?
The normal white-space behavior is to collapse everything to one space. You can modify it by changing the white-space: css rule to white-space: pre; or white-space: pre-wrap;
See https://developer.mozilla.org/en/CSS/white-space for more details
Multiple spaces are trimmed in the html output of most browsers, not in the html code itself. If you want multiple spaces to render you can use str_replace(" ", " ",$var) which will tell the browsers to render each whitespace character. The same goes for multiple linebreaks, using nl2br()
HTML always strips extra whitespace characters (for displaying). If you want to prevent this use . However it sounds like you are using it for alignment. Never do that!
What if the text changes?
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);
If a user types a really long string it doesn't move onto a 2nd line and will break a page on my site. How do I take that string and remove it completely if it's not a URL?
Why would you want to remove what the user wrote? Instead, wrap it to a new line - there is a function in PHP to do that, called wordwrap
Do you really want to remove the word, or do you just want to prevent it from making your page layout too wide? If the latter is more what you want, consider using CSS to manage the overflow.
For instance:
div {
overflow:hidden;
}
will hide any content that exceeds the div boundary.
Here's more info on CSS overflow:
http://www.w3schools.com/css/pr_pos_overflow.asp
// remove words over 30 chars long
$str = preg_replace('/\S{30,}/', '', $str);
edit: updated per Tim P's suggestion, \S matches any non-space char (the same as [^\s])
Also here is a better way incorporating ehdv's suggestion to use wordwrap:
//This will break up the long words with spaces so they don't stretch layouts.
$str = preg_replace('/(\S{30,})/e', "wordwrap('$1', 30, ' ', true)", $str);
What if it is a really long URL? At any rate why not just match the text to a valid URL, and only accept those? Check out some php-regex info on URLs and see how they work. The Regular Expressions Cookbook has a good chapter on URL matching, as well.
#Rob care in using REGEX. Performance lookout.