October 27, 2012

Custom Number format and images in between

Question by Maarten Hartman

I’d like to format a number(stored as 10000.23, or 1.23) with php, , and place images between them, like the following.

10000,23

becomes

[img1]100[img2]00[img3]10

and

1,10

becomes

[img1]0[img2]1[img3]10

Anyone knows how to do this?

I tried several number formats but none of them allowed me to separate the last 4 digits into two pairs ( 00.00.00 )

Answer by Starx

Looks as if you want currency Format and replace the quotation marks with images. Here is a small function to add commas on the number.

function cFormat($number) {
    while (true) {
        $replaced = preg_replace('/(-?d+)(ddd)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

Then, here is how to replace them with images.

$int = 10000.23;
$int = cFormat($int);

// After adding comma, use str_replace() to replace comma with images
$int = str_replace(",", "<img src="comma.jpg" />", $int);
$int = str_replace(".", "<img src="period.jpg" />", $int);
May 28, 2012

PHP Currency Regular Expression

Question by Lee

I am trying to find a piece of regex to match a currency value.

I would like to match only numbers and 1 decimal point ie

Allowed

  • 10
  • 100
  • 100.00

Not Allowed

  • Alpha Characters
  • 100,00
  • +/- 100

I have search and tried quite a few without any luck.

Hope you can advise

Answer by The Pixel Developer

if (preg_match('/^[0-9]+(?:.[0-9]+)?$/im', $subject))
{
    # Successful match
}
else
{
    # Match attempt failed
}

Side note : If you want to restrict how many decimal places you want, you can do something like this :

/^[0-9]+(?:.[0-9]{1,3})?$/im

So

100.000

will match, whereas

100.0001

wont.

If you need any further help, post a comment.

PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.

Answer by Starx

How about this

if (preg_match('/^d+(.d{2})?$/', $subject))
{
   // correct currency format
} else {
  //invalid currency format
}
January 9, 2011

PHP date(): minutes without leading zeros

Question by JamWaffles

I’d like to know if there is a formatting letter for PHP’s date() that allows me to print minutes without leading zeros, or whether I have to manually test for and remove leading zeros?

Answer by Hippo

Use:

$minutes = intval(date('i'));

Answer by Starx

This also works

$timestamp = time(); //Or Your timestamp
echo (int)date('i',$timestamp);
...

Please fill the form - I will response as fast as I can!