I'm building a counter that counts and displays on a web page the number of images in a certain directory.
The code I'm currently using is this:
<?
$d = opendir("images/myimagefolder");
$count = 0;
$min_digits = 7;
while(($f = readdir($d)) !== false)
if(ereg('.jpg$', $f))
++$count;
closedir($d);
if ($min_digits)
{
$count = sprintf('%0'.$min_digits.'f', $count);
}
$number = $count;
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split($formattedNumber, 3);
$formattedNumber = implode(",", $formattedNumber);
print "$formattedNumber";
?>
This works well and outputs a number like the following: 000,000,5
What I am wanting is to have the separating commas occur every 3 digits from the right not the left, so it would appear as 0,000,005
How would this this be done?
I have tried a number of modifications to my sprintf and str_split code but nothing has worked so far. Any help would be greatly appreciated!
<?php
//image count
$images=count(glob("images/myimagefolder/*.jpg"));
//padding
$images=sprintf("%07s",$images);
//commas
$images=strrev(implode(",",str_split(strrev($images),3)));
//outputs 0,000,005
echo $images;
?>
Had a bit of fun coming up with the shortest possible way to accomplish your solution. :)
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split(strrev($formattedNumber), 3);
for (i=0;i<count($formattedNumber); i++)
$formattedNumber[i] = strrev($formattedNumber[i]);
$formattedNumber = implode(",", array_reverse($formattedNumber));
Drop the last four lines. All you need is 'print number_format ($count);'
http://php.net/manual/en/function.number-format.php
Edit, the above won't work with the leading 0's
I found this in the comments on the php site. A little regex magic should do it in one line.
print preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$count);
Here's my take with arrays:
$num = sprintf("%07d", 5);
$digits = str_split($num, 1);
$digits = array_reverse($digits);
$chunks = array_map('array_reverse', array_reverse(array_chunk($digits, 3)));
$concat_chunks = array();
foreach ($chunks as $chunk) {
$concat_chunks[] = join('', $chunk);
}
$output = join(',', $concat_chunks);
print $output;
Related
I want to convert any number which ends in .5 so that it displays as the number followed by ½, but I don't want 0.5 to display as 0½ so I did it like this:
$used = str_replace("0.5", "½", $used);
$used = str_replace(".5", "½", $used);
However I've now realised that this also converts 20.5 into 2½ instead of 20½.
I'm sure there's a better way of doing it but I don't know how.
Examples:
5 returns "5"
5.5 returns "5½"
0.5 returns "½"
10.5 returns "10½"
I don't believe this is a duplicate of an existing question because that code is to replace or return "1/2" rather than "½"
Based on the examples above and lacking any further requirements, you could write:
<?php
$n = "13.5";
/* ... */
$r = $n;
$r = preg_replace ('/^0\.5$/', '½', $r);
$r = preg_replace ('/\.5$/', '½', $r);
echo "$r\n";
You can combine the above into a single replacement:
$r = preg_replace ('/(^0|)\.5$/', '½', $n);
PHP code demo(In HTML it will work fine)
<?php
$number="10.5000";
if(preg_match("/^[1-9][0-9]*\.5[0]{0,}$/", $number))
{
echo $used = preg_replace("/\.5[0]{0,}$/", "½", $number);
}
elseif(preg_match("/^[0]*\.5[0]{0,}$/", $number))
{
echo $used = str_replace("$number", "½", $number);
}
else
{
echo $number;
}
Output:
10½
how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?
This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!
I have a PHP variable that looks a bit like this:
$id = "01922312";
I need to replace the last two or three numbers with another character. How can I go about doing this?
EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:
$new = "01922xxx";
Try this:
$new = substr($id, 0, -3) . 'xxx';
Result:
01922xxx
You can use substr_replace to replace a substring.
$id = substr_replace($id, 'xxx', -3);
Reference:
http://php.net/substr-replace
function replaceCharsInNumber($num, $chars) {
return substr((string) $num, 0, -strlen($chars)) . $chars;
}
Usage:
$number = 5069695;
echo replaceCharsInNumber($number, 'xxx'); //5069xxx
See it in action here: http://codepad.org/XGyVQ1hk
Strings can be treated as arrays, with the characters being the keys:
$id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero.
$id_str = strval($id);
for ($i = 0; $i < count($id_str); $i++)
{
print($id_str[$i]);
}
This should output your original number. Now to do stuff with it, treat it as a normal array:
$id_str[count($id_str) - 1] = 'x';
$id_str[count($id_str) - 2] = 'y';
$id_str[count($id_str) - 3] = 'z';
Hope this helps!
Just convert to string and replace...
$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';
We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.
Solution:
$start_time = '1030';
$pattern = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);
//result: 1050
I've tried to do a number(decimal) increment which looks like 001 002 003...123,124 in a loop and couldn't find a simple solution.What I've thought now is to check out whether the number is long enough ,if not prefix it some "0".But it seems not good.Any better ideas?
Thanks.
$x = 6
$y = sprintf("%03d",$x);
http://php.net/manual/en/function.sprintf.php
for($i=1;$i<1000;$i++){
$number = sprintf("%03d",$i);
echo "$number <br />";
}
Two options come immediately to mind. First, try str_pad(). It does exactly what you seem to describe.
Second, you could use sprintf() as another has suggested.
If you are not sure how long the various numbers will turn out to be (e.g., they are determined dynamically and no way of knowing what they will be until afterwards), you can use the following code:
<?php
$numbers = array();
for ($i = 0; $i < 2000; $i++)
{
$numbers[] = $i;
}
array_walk($numbers, function(&$item, $key, $len) { $item = sprintf('%0'.$len.'d', $item); }, strlen(max($numbers)));
print_r($numbers);
?>
I'd like to get all the permutations of swapped characters pairs of a string. For example:
Base string: abcd
Combinations:
bacd
acbd
abdc
etc.
Edit
I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.
What's the best way to do this?
Edit
Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?
Speed test
I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)
Edit: Markdown hates me today...
$input = "abcd";
$len = strlen($input);
$output = array();
for ($i = 0; $i < $len - 1; ++$i) {
$output[] = substr($input, 0, $i)
. substr($input, $i + 1, 1)
. substr($input, $i, 1)
. substr($input, $i + 2);
}
print_r($output);
nickf made beautiful solution thank you , i came up with less beautiful:
$arr=array(0=>'a',1=>'b',2=>'c',3=>'d');
for($i=0;$i<count($arr)-1;$i++){
$swapped="";
//Make normal before swapped
for($z=0;$z<$i;$z++){
$swapped.=$arr[$z];
}
//Create swapped
$i1=$i+1;
$swapped.=$arr[$i1].$arr[$i];
//Make normal after swapped.
for($y=$z+2;$y<count($arr);$y++){
$swapped.=$arr[$y];
}
$arrayswapped[$i]=$swapped;
}
var_dump($arrayswapped);
A fast search in google gave me that:
http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/
How about just using the following:
function swap($s, $i)
{
$t = $s[$i];
$s[$i] = $s[$i+1];
$s[$i+1] = $t;
return $s;
}
$s = "abcd";
$l = strlen($s);
for ($i=0; $i<$l-1; ++$i)
{
print swap($s,$i)."\n";
}
Here is a slightly faster solution as its not overusing substr().
function swapcharpairs($input = "abcd") {
$pre = "";
$a="";
$b = $input[0];
$post = substr($input, 1);
while($post!='') {
$pre.=$a;
$a=$b;
$b=$post[0];
$post=substr($post,1);
$swaps[] = $pre.$b.$a.$post;
};
return $swaps;
}
print_R(swapcharpairs());