PHP sprintf space padding - php

I have the following line in my code which displays my output in 6 characters with leading zeros.
$formatted_value = sprintf("%06d", $phpPartHrsMls);
I want to replace the leading zeros with spaces. Have tried all the examples found by searching this site and others and cannot figure it out.
Here are some I have tried:
$formatted_value = sprintf("%6s", $phpPartHrsMls);
$formatted_value = printf("[%6s]\n", $phpPartHrsMls); // right-justification with spaces

In the browser, spaces will always be collapsed.
Try:
<pre><?php echo $formatted_value; ?></pre>
And once you're satisfied with that, take a look at the CSS white-space:pre-wrap - a very useful property!

This will align the left with spaces:
$formatted_value = sprintf("%6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
This will align the right with spaces:
$formatted_value = sprintf("%-6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
If you want to print only six digits, and others to remove:
$formatted_value = sprintf("%-6.6s", $phpPartHrsMls);
echo "<pre>" . $formatted_value . "</pre>";
One more thing, the browser will generally ignore the spaces, so it's better to wrap your output in <pre> tag.

Changing leading zeroes to leading spaces:
$formatted_value = sprintf("%' 6s", $phpPartHrsMls);

Try str_pad.
str_pad($phpPartHrsMls, 6, " ", STR_PAD_LEFT);

you use %06d please try some larger number .
your code can some thing like below try :
printf('%20.2f', $phpPartHrsMls);
and you can use for space on your html .

Related

using fpdf : str_pad doesn't work with spaces, it works with other characters

I am adding a pad to my string, to fill with spaces, but it doesn't work
the code is here
<?php
$string1 = "Product 1 ";
$newString = str_pad($string1,100);
echo $newString."test";
echo "<br>";
$string2 = "Product 2222 ";
echo str_pad($string2,100," ")."test";
echo "<br>";
?>
the output is like this:
Product 1 test
Product 2222 test
You could try $str = str_pad($string2,(100*strlen(" "))," ")."test"; instead.
renders to a non-breaking-space in html (and when writing to document with fpdf).
Please note this can only work with fpdf when you tell it to write all lines as html! And the encoding should be utf-8 probably
$fpdf->Write(iconv('UTF-8', 'windows-1252', html_entity_decode($str)));
When the output of the PHP is converted to HTML, all the white spaces except the first are removed and it is the default feature of HTML and web browsers. so the output will not be correct.
You have to use the " " instead of white space in the str_pad function. HTML don't ignore the " " and against each existance of it, HTML adds a white space to the string.

str_ireplace or preg_replace replaced break tag into \r\n

I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

str_replace - doesn't work when using "< >"

I've got a problem with str_replace.
I have scraped a page with curl and now I want to replace an href id like this:
(all variables are present)
$search_result = str_replace("<href=\"?run=".$id."\">", "<href=\"?run=1111\">", $search_result);
The problem is that when I use the "<" and ">" characters in the str_replace it will not work.
Can anyone tell me why?
I also tried this (which does work like expected):
$test = "< something >";
$test = str_replace("<", "(", $test);
echo $test;
i'm not sure to have understand your question...
$test = "< something >";
$test = str_replace("<", "(", $test);
$test = str_replace(">", ")", $test);
echo $test;
this give me this output
( something )
so it works!
and doing a little mod to your code works fine on me, just try this:
$link = "hello world";
$search_result = str_replace('<a href="?run=1">', "<a href=\"?run=1111\">", $link);
echo $search_result;
Use this regular expression to replace the multiple occurance , as < and . are escape characters we have to escape them as shown below
value.replace(/>/g, '(');

Remove ZERO WIDTH NON-JOINER character from a string in PHP

I want to remove ZERO WIDTH NON-JOINER character from a string but using str_replace wasn't useful.
str_replace should solves this, as long as you're careful with what you're replacing.
// \xE2\x80\x8C is ZERO WIDTH NON-JOINER
$foo = "foo\xE2\x80\x8Cbar";
print($foo . " - " . strlen($foo) . "\n");
$foo = str_replace("\xE2\x80\x8C", "", $foo);
print($foo . " - " . strlen($foo) . "\n");
Outputs as expected:
foo‌bar - 9
foobar - 6
str_replace will do what you want, but PHP does not have very good native support for Unicode. The following will do what you ask. json_decode has been used to get the Unicode char, since PHP does not support the \u syntax.
<?php
$unicodeChar = json_decode('"\u200c"');
$string = 'blah'.$unicodeChar.'blah';
echo str_replace($unicodeChar, '', $string);
?>
edit: While my method works, I would suggest you use fiskfisk's solution. It is less hacky than using json_decode.

printing a php variable as it is : with all the special characters

Ok I need to find out what is contained inside a PHP variable and I have it to do it visually, is there a function to display whatever that's contained in a string as it is?
For example :
$TEST = '&nbsp' . "\n" . ' ';
if I use echo the output will be :
while i want it to be :
&nbsp\n&nbsp
is it possible? (I hope I was clear enough)
ty
You can use json_encode with htmlspecialchars:
$TEST = ' ' . "\n" . ' ';
echo json_encode(htmlspecialchars($TEST));
Note that json_encode has third agrument in PHP 5.4.
var_dump() should do the work for you?
Example:
echo "<pre>";
var_dump($variable);
echo "</pre>";
Use <pre> to keep the format structure, makes it alot easier to read.
Resources:
http://php.net/manual/en/function.var-dump.php
http://www.w3schools.com/tags/tag_pre.asp
Try print_r, var_dump or var_export functions, you'll find them very handy for this kind of needs!
http://www.php.net/manual/en/function.htmlspecialchars.php
or
http://www.php.net/manual/en/function.htmlentities.php
$TEST = '&nbsp' . "\n" . ' ';
echo htmlspecialchars(str_replace('\n','\\n', $TEST), ENT_QUOTES);
or
$TEST = '&nbsp' . "\n" . ' ';
echo htmlentities(str_replace('\n','\\n',$TEST), ENT_QUOTES);
You may have to encode the newlines manually. If you want to encode them as actual newlines you can use nl2br. Or string replace these characters with your preference. Update: as I have added to the code per request. String replace special characters you wish to see like newlines and tabs.
assuming you want it for the debugging purposes, let me suggest to use urlencode(). I am using it to make sure I don't miss any invisible character.
The output is not that clear but it works for me.

Categories