Skip to content
This repository was archived by the owner on Jul 30, 2026. It is now read-only.

Formatting

Josh edited this page Apr 23, 2018 · 5 revisions

This class contains functions to help (re)format data.

Use:
\blobfolio\common\format (by value)
\blobfolio\common\ref\format (by reference)

array_flatten()

Push all values in a multi-dimensional array into a sequential, single-dimensional array.

Versions

  • By Value
  • By Reference

Arguments

Type Description
array Array.

Returns

If passing by value a new array is returned, otherwise TRUE.

Example

$arr = array(1, array(2, array(3)));
\blobfolio\common\ref\format::array_flatten($arr); // [1, 2, 3]

array_to_indexed()

Rebuild a key=>value array so that each value is an array containing the original key and value. This can be helpful if exporting associative array data to Javascript, for example.

Versions

  • By Value
  • By Reference

Arguments

Type Description
array Array.

Returns

If passing by value a new array is returned, otherwise TRUE.

Example

$arr = array(
    'fruit'=>'apple',
    'vegetable'=>'carrot'
);
\blobfolio\common\format::array_to_indexed($arr);
/*
array(
    0 => array(
        [key] => fruit,
        [value] => apple
    ),
    1 => array(
        [key] => vegetable,
        [value] => carrot
    )
)
*/

cidr_to_range()

Convert a CIDR to a minimum/maximum range of IPs.

Arguments

Type Description
string CIDR.

Returns

Returns an array with "min" and "max" IPs or FALSE on failure.

Example

\blobfolio\common\format::cidr_to_range('2600:3c00::f03c:91ff:feae:0ff2/64');
/*
array(
    [min] => 2600:3c00::f03c:91ff:feae:ff2,
    [max] => 2600:3c00::ffff:ffff:ffff:ffff
)
*/

ceil()

This is just like PHP's ceil() function, except that you can specify a decimal precision.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Number(s). If an array is passed, each value will be processed recursively.
int Precision. 0

Returns

If passing by value the rounded value is returned as a float, otherwise TRUE.

decode_entities()

Convert as many HTML entities to their character counterpoints as possible with as many passes as it takes to get them all.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string HTML.

Returns

If passing by value a decoded string is returned, otherwise TRUE.

Example

\blobfolio\common\format::decode_entities('"Happy Days"'); // "Happy Days"

decode_escape_entities()

Converts the following back to actual characters: \b, \f, \n, \r, \t.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string String.

Returns

If passing by value a decoded string is returned, otherwise TRUE.

decode_js_entities()

Shorthand for running both ::decode_unicode_entities() and ::decode_escape_entities().

Versions

  • By Value
  • By Reference

Arguments

Type Description
string String.

Returns

If passing by value a decoded string is returned, otherwise TRUE.

decode_unicode_entities()

Converts Unicode like \u0000 to an actual character.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string String.

Returns

If passing by value a decoded string is returned, otherwise TRUE.

excerpt()

Shorten text to a set number of letters or words. This function is multi-byte safe provided mbstring is present.

Arguments

Type Description Notes
string String.
array Options. See below.

Options:

Type Description Notes Default
int Length. The maximum string length. 200
string Suffix. A suffix to indicate that the string has been shortened. "…"
string Unit. Either "character" or "word". "character"

Returns

Returns the original or truncated string.

Example

$str = "Hey good lookin'";
$foo = \blobfolio\common\format::excerpt($str, array('length'=>5, 'unit'=>'character')); // Hey g…
$foo = \blobfolio\common\format::excerpt($str, array('length'=>2, 'unit'=>'word')); // Hey good…

floor()

This is just like PHP's floor() function, except that you can specify a decimal precision.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Number(s). If an array is passed, each value will be processed recursively.
int Precision. 0

Returns

If passing by value the rounded value is returned as a float, otherwise TRUE.

fraction()

Convert a decimal to a fraction, e.g. 0.5 becomes "1/2".

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Number(s). If an array is passed, each value will be processed recursively.
float Tolerance. Limit how deep calculations run since decimals can go on forever. Haha. 0.0001

Returns

Returns a string representation of the fraction by value, or TRUE by reference.

Example

echo \blobfolio\common\format::fraction(0.5); // 1/2
echo \blobfolio\common\format::fraction(-0.5); // -1/2
echo \blobfolio\common\format::fraction(5); // 5
echo \blobfolio\common\format::fraction(0.33); // 33/100
echo \blobfolio\common\format::fraction(0.33, 0.1); // 1/3

inflect()

Choose between a singular and plural string given a numerical value. printf() formatting is supported.

Arguments

Type Description Notes
mixed Count. If an array is passed, its count() will be used. Otherwise the value should be numeric.
string Singular.
string Plural.

Returns

Returns the singular string if the count is 1, otherwise the plural string.

Example

echo "I have " . \blobfolio\common\format::inflect(1, '%d book', '%d books'); // I have 1 book

ip_to_number()

Convert an IPv4 or IPv6 address to its numerical equivalent. This requires the PHP extensions bcmath or gmp.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string IP address.

Returns

If passed by value, returns the numerical IP address or FALSE, otherwise TRUE/FALSE.

Example

// By value.
$foo = \blobfolio\common\format::ip_to_number('50.116.18.174'); // 846467758

// By reference.
\blobfolio\common\ref\format::ip_to_number($foo);

ip_to_subnet()

Retrieve the subnet range for an IP address. This assumes /24 for IPv4 and /64 for IPv6. This requires the PHP extensions bcmath or gmp.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string IP address.

Returns

If passed by value, returns the subnet or FALSE, otherwise TRUE/FALSE.

Example

// By value.
$foo = \blobfolio\common\format::ip_to_subnet('50.116.18.174'); // 50.116.18.0/24

// By reference.
\blobfolio\common\ref\format::ip_to_subnet($foo);

json()

Convert a JSON or JSON-like string into proper JSON. This will fix key/value quoting, remove comments, remove trailing commas, correct UTF-8 issues, etc.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Data. If a JSON(ish) string is passed, its formatting will be sanitized/corrected; if something else is passed, it will be converted to JSON.
bool Pretty print. If TRUE, output will be pretty-printed. TRUE

Returns

If passed by value, returns JSON string or NULL, otherwise TRUE/FALSE.

json_decode()

A json_decode() wrapper that applies the same formatting forgiveness as the above ::json() function, giving the data a fighting chance of coming through.

Note: This always returns objecty data as an associative array.

Versions

  • By Value
  • By Reference

Arguments

Type Description
string JSON.

Returns

If passed by value, returns the decoded data, otherwise TRUE/FALSE.

links()

Convert plain-text URLs, domains, email addresses, and telephone numbers into clickable (HTML) links.

Malformed data will be left alone, as will any non-FQDN domain or email address.

Unicode hosts are supported if the PHP extension intl is installed, but the resulting href attribute will be converted to Punycode/ASCII.

People are very inconsistent at how they write telephone numbers. This looks specifically for international formatting (+1 201-555-0123), or common North American 10-digit representations like (201) 555-0123, 201-555-0123, 201.555.0123, etc. Other types of numbery bits, or phone-ish strings that don't validate, will be ignored.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes
string String.
array Attributes. Attributes to add to generated links. See below.

All attributes are optional.

Type Key Description
string, array class Class(es).
string rel Relation.
string target Target.

Returns

If passed by value, returns the text with added links, otherwise TRUE.

Example

// By value.
$foo = \blobfolio\common\format::links('Welcome to domain.com!'); // Welcome to <a href="http://domain.com">domain.com</a>!

$args = array(
  'target'=>'_blank'
);
$foo = \blobfolio\common\format::links('me@domain.com', $args); // <a href="mailto:me@domain.com" target="_blank">me@domain.com</a>

// By reference.
\blobfolio\common\ref\format::links($foo);

list_to_array()

Convert a delimited list, or array of delimited lists, into a normal, single-dimensional array.

This is useful, e.g., in parsing function arguments that might be passed as proper arrays or comma-delimited strings.

Note: empty values are always ignored, but other types of falsey values are fine.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes
mixed List.
array Options. See below for details.

Returns

If passed by value, returns an array of values, otherwise TRUE.

Example

// Possible arguments, defaults shown.
$args = array(
  'delimiter'=>',', // List delimiter.
  'cast'=>'string', // Cast output values as this type.
  
  'trim'=>true,     // Trim values, so e.g. "1, 2" and "1,2" wind up the same.
  'min'=>null,      // Remove values less than this.
  'max'=>null,      // Remove values greater than this.

  'unique'=>true,   // Remove duplicate values.
  'sort'=>false,    // Sort values.
);

// By value.
$foo = \blobfolio\common\format::list_to_array('1,,2,3', $args); // [1, 2, 3]

$args = array(
  'min'=>'2'
);
$foo = \blobfolio\common\format::list_to_array('1,2,3', $args); // [2,3]

// By reference.
blobfolio\common\ref\format::list_to_array($foo, $args);

money()

Format a value as US currency.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Amount. If an array is passed, each value will be processed recursively.
bool Cents. If TRUE, sub-dollar values will be formatted like "50¢". FALSE
string Thousands separator. ""
bool Remove trailing .00. If TRUE, cents will be stripped off whole-dollar amounts. FALSE

Returns

If passing by value, returns the formatted amount, otherwise TRUE.

// By value.
$foo = \blobfolio\common\format::money(.75, true); // 75¢
$foo = \blobfolio\common\format::money(.75, false); // $0.75

// By reference.
\blobfolio\common\ref\format::money($foo);

number_to_ip()

Like long2ip but capable of handling IPv6. This requires the PHP extensions bcmath or gmp.

Versions

  • By Value
  • By Reference

Arguments

Type Description
int, string Decimal IP address.

Returns

If passed by value, returns the IP address or FALSE, otherwise TRUE/FALSE.

Example

// By value.
$foo = \blobfolio\common\format::number_to_ip(846467758); // 50.116.18.174

// By reference.
\blobfolio\common\ref\format::number_to_ip($foo);

phone()

Format and verify a phone number using international formatting. This uses blob-phone for extra-strength goodness.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
string Phone number.
string (Suspected) Country. Providing the suspected country of origin helps with identification, as there is some overlap in formatting rules. "US"
array Type(s) Require specific type(s) of number. See below. NULL

Phone number types:

  • "fixed", i.e. landline
  • "mobile"
  • "pager"
  • "personal_number"
  • "premium_rate", e.g. your favorite party line
  • "shared_cost"
  • "toll_free"
  • "voicemail"
  • "voip", e.g. Google Voice

Returns

Returns "" if the number is invalid, otherwise the number in proper international format. If passing by reference TRUE or FALSE is returned.

Example

// By value.
$foo = \blobfolio\common\format::phone('(555) 618-2086'); // +1 555-608-2086

// By reference.
\blobfolio\common\ref\format::phone($foo);

round()

This is just like PHP's round() function, except that you can pass an array of values to process recursively if desired.

Versions

  • By Value
  • By Reference

Arguments

Type Description Notes Default
mixed Number(s). If an array is passed, each value will be processed recursively.
int Precision. 0
int Rounding mode. See round() for possible values. PHP_ROUND_HALF_UP

Returns

If passing by value the rounded value is returned as a float, otherwise TRUE.

to_csv()

Convert a dataset to CSV format.

Arguments

Type Description Notes Default
array Data. This should be an array of arrays, the outer being rows, the inner being columns.
array Headers. A header row will be inserted using these values, if provided, or the associative keys of the first data row, if applicable. NULL
string Column separator. ","
string Row separator "\n"

Returns

Returns a string containing the CSV content.

Example

$data = array(
    array('John','Doe','01/01/2000'),
    array('Jane','Doe','12/25/1998')
);
$headers = array('First', 'Last', 'Joined');

$csv = \blobfolio\common\format::to_csv($data, $headers);

to_timezone()

Convert a datestring from one timezone to another.

Versions

  • By Value
  • By Reference

Arguments

Type Description Default
int, string Date or timestamp.
string From TZ. "UTC"
string To TZ. "UTC"

Example

// By value.
$foo = \blobfolio\common\format::to_timezone('2015:01:01 10:00:00', 'UTC', 'America/Los_Angeles'); // 2015-01-01 02:00:00

// By reference.
\blobfolio\common\ref\format::to_timezone($foo, 'UTC', 'America/Chicago');

to_xls()

Convert a dataset to Microsoft Excel's XML format. Special cell formatting will be used for boolean, numeric, percent, currency, and date values.

Arguments

Type Description Notes Default
array Data. This should be an array of arrays, the outer being rows, the inner being columns.
array Headers. A header row will be inserted using these values, if provided, or the associative keys of the first data row, if applicable. NULL

Returns

Returns a string containing the XML/XLS content.

Example

$data = array(
    array('John','Doe','01/01/2000'),
    array('Jane','Doe','12/25/1998')
);
$headers = array('First', 'Last', 'Joined');

$xls = blobfolio\common\format::to_xls($data, $headers);

CLI

Constants

Dom Helpers

Files and Paths

Formatting

General Data Helpers

Images

Multi-Byte Wrappers

Sanitizing and Validation

Typecasting

Clone this wiki locally