GithubHelp home page GithubHelp logo

php-humanizer's Introduction

PHP Humanizer

Tests Latest Stable Version Total Downloads Latest Unstable Version License

Readme for 5.x version

Humanize values to make them readable for regular people ;)

Installation

Run the following command:

composer require coduo/php-humanizer

Usage

Text

Humanize

use Coduo\PHPHumanizer\StringHumanizer;

StringHumanizer::humanize('field_name'); // "Field Name"
StringHumanizer::humanize('user_id'); // "User"
StringHumanizer::humanize('field_name', false); // "field name"

Truncate

Truncate string to word closest to a certain length

use Coduo\PHPHumanizer\StringHumanizer;

$text = 'Lorem ipsum dolorem si amet, lorem ipsum. Dolorem sic et nunc.';

StringHumanizer::truncate($text, 8); // "Lorem ipsum"
StringHumanizer::truncate($text, 8, '...'); // "Lorem ipsum..."
StringHumanizer::truncate($text, 2); // "Lorem"
StringHumanizer::truncate($text, strlen($text)); // "Lorem ipsum dolorem si amet, lorem ipsum. Dolorem sic et nunc."

Truncate HTML

Truncate and HTML string to word closest to a certain length

use Coduo\PHPHumanizer\StringHumanizer;

$text = '<p><b>HyperText Markup Language</b>, commonly referred to as <b>HTML</b>, is the standard <a href="/wiki/Markup_language" title="Markup language">markup language</a> used to create <a href="/wiki/Web_page" title="Web page">web pages</a>.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span>[</span>1<span>]</span></a></sup> <a href="/wiki/Web_browser" title="Web browser">Web browsers</a> can read HTML files and render them into visible or audible web pages. HTML describes the structure of a <a href="/wiki/Website" title="Website">website</a> <a href="/wiki/Semantic" title="Semantic" class="mw-redirect">semantically</a> along with cues for presentation, making it a markup language, rather than a <a href="/wiki/Programming_language" title="Programming language">programming language</a>.</p>';

StringHumanizer::truncateHtml($text, 3); // "<b>HyperText</b>"
StringHumanizer::truncateHtml($text, 12, ''); // "HyperText Markup"
StringHumanizer::truncateHtml($text, 50, '', '...'); // "HyperText Markup Language, commonly referred to as..."
StringHumanizer::truncateHtml($text, 75, '<b><i><u><em><strong><a><span>', '...'); // '<b>HyperText Markup Language</b>, commonly referred to as <b>HTML</b>, is the standard <a href="/wiki/Markup_language" title="Markup language">markup...</a>'

Remove shortcodes

$text = 'A text with [short]random[/short] [codes]words[/codes].';
StringHumanizer::removeShortcodes($text); // "A text with ."
StringHumanizer::removeShortcodeTags($text); // "A text with random words."

Number

Ordinalize

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::ordinalize(0); // "0th"
NumberHumanizer::ordinalize(1); // "1st"
NumberHumanizer::ordinalize(2); // "2nd"
NumberHumanizer::ordinalize(23); // "23rd"
NumberHumanizer::ordinalize(1002, 'nl'); // "1002e"
NumberHumanizer::ordinalize(-111); // "-111th"

Ordinal

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::ordinal(0); // "th"
NumberHumanizer::ordinal(1); // "st"
NumberHumanizer::ordinal(2); // "nd"
NumberHumanizer::ordinal(23); // "rd"
NumberHumanizer::ordinal(1002); // "nd"
NumberHumanizer::ordinal(-111, 'nl'); // "e"

Roman numbers

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::toRoman(1); // "I"
NumberHumanizer::toRoman(5); // "V"
NumberHumanizer::toRoman(1300); // "MCCC"

NumberHumanizer::fromRoman("MMMCMXCIX"); // 3999
NumberHumanizer::fromRoman("V"); // 5
NumberHumanizer::fromRoman("CXXV"); // 125

Binary Suffix

Convert a number of bytes in to the highest applicable data unit

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::binarySuffix(0); // "0 bytes"
NumberHumanizer::binarySuffix(1); // "1 bytes"
NumberHumanizer::binarySuffix(1024); // "1 kB"
NumberHumanizer::binarySuffix(1025); // "1 kB"
NumberHumanizer::binarySuffix(1536); // "1.5 kB"
NumberHumanizer::binarySuffix(1048576 * 5); // "5 MB"
NumberHumanizer::binarySuffix(1073741824 * 2); // "2 GB"
NumberHumanizer::binarySuffix(1099511627776 * 3); // "3 TB"
NumberHumanizer::binarySuffix(1325899906842624); // "1.18 PB"

Number can be also formatted for specific locale

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::binarySuffix(1536, 'pl'); // "1,5 kB"

Number can also be humanized with a specific number of decimal places with preciseBinarySuffix($number, $precision, $locale = 'en') The precision parameter must be between 0 and 3.

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::preciseBinarySuffix(1024, 2); // "1.00 kB"
NumberHumanizer::preciseBinarySuffix(1325899906842624, 3); // "1.178 PB"

This function also supports locale

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::preciseBinarySuffix(1325899906842624, 3, 'pl'); // "1,178 PB"

Metric Suffix

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::metricSuffix(-1); // "-1"
NumberHumanizer::metricSuffix(0); // "0"
NumberHumanizer::metricSuffix(1); // "1"
NumberHumanizer::metricSuffix(101); // "101"
NumberHumanizer::metricSuffix(1000); // "1k"
NumberHumanizer::metricSuffix(1240); // "1.2k"
NumberHumanizer::metricSuffix(1240000); // "1.24M"
NumberHumanizer::metricSuffix(3500000); // "3.5M"

Number can be also formatted for specific locale

use Coduo\PHPHumanizer\NumberHumanizer;

NumberHumanizer::metricSuffix(1240000, 'pl'); // "1,24M"

Collections

Oxford

use Coduo\PHPHumanizer\CollectionHumanizer;

CollectionHumanizer::oxford(['Michal', 'Norbert', 'Lukasz', 'Pawel'], 2); // "Michal, Norbert, and 2 others"
CollectionHumanizer::oxford(['Michal', 'Norbert', 'Lukasz'], 2); // "Michal, Norbert, and 1 other"
CollectionHumanizer::oxford(['Michal', 'Norbert']); // "Michal and Norbert"

Oxford is using translator component, so you can use whatever string format you like.

Date time

Difference

use Coduo\PHPHumanizer\DateTimeHumanizer;

DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 13:00:00")); // just now
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 13:00:05")); // 5 seconds from now
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 12:59:00")); // 1 minute ago
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 12:45:00")); // 15 minutes ago
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 13:15:00")); // 15 minutes from now
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 14:00:00")); // 1 hour from now
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 15:00:00")); // 2 hours from now
DateTimeHumanizer::difference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-26 12:00:00")); // 1 hour ago
DateTimeHumanizer::difference(new \DateTime("2014-04-26"), new \DateTime("2014-04-25")); // 1 day ago
DateTimeHumanizer::difference(new \DateTime("2014-04-26"), new \DateTime("2014-04-24")); // 2 days ago
DateTimeHumanizer::difference(new \DateTime("2014-04-26"), new \DateTime("2014-04-28")); // 2 days from now
DateTimeHumanizer::difference(new \DateTime("2014-04-01"), new \DateTime("2014-04-15")); // 2 weeks from now
DateTimeHumanizer::difference(new \DateTime("2014-04-15"), new \DateTime("2014-04-07")); // 1 week ago
DateTimeHumanizer::difference(new \DateTime("2014-01-01"), new \DateTime("2014-04-01")); // 3 months from now
DateTimeHumanizer::difference(new \DateTime("2014-05-01"), new \DateTime("2014-04-01")); // 1 month ago
DateTimeHumanizer::difference(new \DateTime("2015-05-01"), new \DateTime("2014-04-01")); // 1 year ago
DateTimeHumanizer::difference(new \DateTime("2014-05-01"), new \DateTime("2016-04-01")); // 2 years from now

Precise difference

use Coduo\PHPHumanizer\DateTimeHumanizer;

DateTimeHumanizer::preciseDifference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2014-04-25 11:20:00")); // 1 day, 1 hour, 40 minutes ago
DateTimeHumanizer::preciseDifference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2015-04-28 17:00:00")); // 1 year, 2 days, 4 hours from now
DateTimeHumanizer::preciseDifference(new \DateTime("2014-04-26 13:00:00"), new \DateTime("2016-04-27 13:00:00")); // 2 years, 1 day from now

Aeon Calendar

Aeon PHP is a date&time oriented set of libraries.

use Coduo\PHPHumanizer\DateTimeHumanizer;

$timeUnit = TimeUnit::days(2)
                ->add(TimeUnit::hours(3))
                ->add(TimeUnit::minutes(25))
                ->add(TimeUnit::seconds(30))
                ->add(TimeUnit::milliseconds(200));
            
DateTimeHumanizer::timeUnit($timeUnit); // 2 days, 3 hours, 25 minutes, and 30.2 seconds

Currently we support following languages:

Development

After downloading library update dependencies:

composer update

In order to check lowest possible versions of dependencies add

composer update --prefer-lowest

Execute test suite:

composer run test

Run CS Fixer

composer run cs:php:fix

Credits

This lib was inspired by Java Humanize Lib && Rails Active Support

php-humanizer's People

Contributors

4t87ux8 avatar aeon-automation avatar arrowrowe avatar borales avatar brianwozeniak avatar dagaa avatar defrag avatar doenietzomoeilijk avatar hyperpanic avatar isnani avatar jebog avatar lpopov avatar mattallty avatar mostertb avatar naprirfan avatar norberttech avatar nwatth avatar omissis avatar ozmodiar avatar pborreli avatar percymamedy avatar peter279k avatar sam002 avatar sarelvdwalt avatar serima avatar tbreuss avatar thunderer avatar vinicius73 avatar vinkla avatar zae avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-humanizer's Issues

Problem with big numbers

Try use this function
echo NumberHumanizer::metricSuffix(1240);
but always return "-0P"

Problem with big number, two array keys on \Coduo\PHPHumanizer\String\MetricSuffix $binaryPrefixes have wrong values when use print_r for this class:
Array ( [-1530494976] => #.##P [-727379968] => #.##T [1000000000] => #.##G [1000000] => #.##M [1000] => #.#k [0] => #.# )

how I can resolve this? sorry for my english =)

Make the CollectionHumanizer::oxford to accept an \Iterator interface

What is the Idea?

The idea is to improve the make Coduo\PHPHumanizer\CollectionHumanizer::oxford() accept an \Iterator interface instead of an array always.
With this, We could send real collections, arrays, etc.
To make it work, all We will need is to iterate it (call the array_map as it's being done) and rely on a possible toString implementation, in case it doesn't have OR the result of each iteration is not a string eligible/parseable, so, We just throw an exception.

I can submit a PR with the idea if you guys agree with the improvement.

Support for English formats

Introduce support of English notation.

Currenlty 1*10^9 is represented as 1G, should be 1B (billion) and etc.

String::truncate() support for html text

It would be great if String::truncate() would also support truncating text with html tags (and not breaking everything with orphan tags) since this is quite common problem in any website which accepts user text content

Support for IEC standard prefixes and suffix translation

I would also being able to use the standard IEC binary prefixes such as "Mi" and "Gi" instead of "M" and "G" in BinarySuffix functions and to use a localized suffix as in french we commonly use "o" instead of "B" (we use "octet(s)" instead of "byte(s)").
I can understand that replacing "GB" by "GiB" by default is counterintuitive as it's not the most commonly used spelling so it could be achieved adding another parameter or usng a "tweaked" locale.
The result could be something like this:

echo Number::binarySuffix(1073741824 * 2); // "2 GiB"
echo Number::binarySuffix(1073741824 * 2, 'en-iec'); // "2 GiB"
echo Number::binarySuffix(1073741824 * 2, 'fr'); // "2 Go"
echo Number::binarySuffix(1073741824 * 2, 'fr-iec'); // "2 Gio"

Update Composer to support later version of Symfony 4.2

Could you update your minimum requirements to allow later version of Symfony. You have these:

        "symfony/config": "^2.3|^3.0|^4.0",
        "symfony/translation": "^2.3|^3.0|^4.0",
        "symfony/yaml": "^2.3|^3.0|^4.0",

This would allow for those symfony packages from 4.0 up to but not including 4.1 or anything greater. I have other packages that want to use Symfony 4.2. Could you be less restrictive on these, maybe this:

        "symfony/config": "^2.3|^3.0|^4",
        "symfony/translation": "^2.3|^3.0|^4",
        "symfony/yaml": "^2.3|^3.0|^4",

Then anything 4.x would install, or if you don't want to do that update to support 4.2.x? Thanks!

Is Symfony really required?

Composer said that Symfony is required for php-humanizer. Is that correct?

IMO: That would be a bit too much just for this little framework 😮

PHP 7 private word

Hi,
In PhP7 the word String by example is a protected word by native type

Psr-4 autoloading standard

Hi i have a problem with your package
Deprecation Notice: Class Coduo\PHPHumanizer\Tests\CollectionHumanizerTest located in ./vendor/coduo/php-humanizer/tests/Coduo/PHPHumanizer/Tests/CollectionHumanizerTest.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201
Can you update it?

Support for different character separators

Currently if I do this:

String::humanize('land-rover');

I get Land-Rover.

Is there any way to support setting a special character modified so that it doesn't always couple to the underscore character?

Division by zero

Hi,

I'm facing an issue on PHP 5.5.9-1ubuntu4.19 (cli) when using NumberHumanizer::binarySuffix as I'm having a PHP warning saying Division by zero.

I digged by myself and found that the array

private $binaryPrefixes = array(
        1125899906842624 => '#.## PB',
        1099511627776 => '#.## TB',
        1073741824 => '#.## GB',
        1048576 => '#.## MB',
        1024 => '#.# kB',
        0 => '# bytes',
    );

is actually returned such as

Array
(
    [0] => # bytes
    [1073741824] => #.## GB
    [1048576] => #.## MB
    [1024] => #.# kB
)

Did anyone faced this issue already?

Thanks by the way

PHP 7 release

Is there a reason why still not exists 2.0 release? it will allow require this package recursively without downgrading stability settings, thanks.
for ex.: my package A uses your package as a dependency (dev-master). when I try to require my package A with default minimum-stability "stable" it fails and I need to downgrade it up to "@dev".

Number::binarySuffix() throws exception when intl extension is missing

 Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("The Symfony\Component\Intl\NumberFormatter\NumberFormatter::__construct() method's argument $style value 0 behavior is not i
mplemented. The available styles are: CURRENCY, DECIMAL..  Please install the "intl" extension for full localization capabilities.") in "AppBundle::bandwidth_usage.html.twig" at line 14." at /var/www/project/vendor/twig/twig/lib/Twig/Template.php line 182 {"exception":"[obj
ect] (Twig_Error_Runtime(code: 0): An exception has been thrown during the rendering of a template (\"The Symfony\\Component\\Intl\\NumberFormatter\\NumberFormatter::__construct() method's argument $style value 0 behavior is not implemented. The available styles are: CURREN
CY, DECIMAL..  Please install the \"intl\" extension for full localization capabilities.\") in \"AppBundle::bandwidth_usage.html.twig\" at line 14. at /var/www/project/vendor/twig/twig/lib/Twig/Template.php:182, Symfony\\Component\\Intl\\Exception\\MethodArgumentValueNotImp
lementedException(code: 0): The Symfony\\Component\\Intl\\NumberFormatter\\NumberFormatter::__construct() method's argument $style value 0 behavior is not implemented. The available styles are: CURRENCY, DECIMAL..  Please install the \"intl\" extension for full localization
 capabilities. at /var/www/project/vendor/symfony/symfony/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php:292)"} []

BinarySuffix Division by zero

While testing i have a division by zero warning.
I'm running humanizer 2.0.0 on windows machine with php 7.1.1

Executed code

print NumberHumanizer::binarySuffix(1025);

Error

Warning: Division by zero in vendor\coduo\php-humanizer\src\Coduo\PHPHumanizer\String\BinarySuffix.php on line 61

Make installable for L9

Problem 1
- coduo/php-humanizer[4.0.0, ..., 4.x-dev] require symfony/translation ^4.4|^5.0 -> found symfony/translation[v4.4.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.4.x-dev] but the package is fixed to v6.0.9 (lock file version) by a partial update and that version does not match. Make sure you list it as an ar
gument for the update command.
- Root composer.json requires coduo/php-humanizer ^4.0 -> satisfiable by coduo/php-humanizer[4.0.0, 4.0.1, 4.0.2, 4.x-dev].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require coduo/php-humanizer:*" to figure out if any version is installable, or "composer require coduo/php-humanizer:^2.1" if you know which you need.

Symfony4 support

It's not possible to use this library in Symfony4 projects of because composer dependencies .. is it possible to add "|^4"?

Bug: uncaught InvalidArgumentException in CollectionHumanizer::oxford with correct input

Test case for coduo/php-humanizer 2.0.0:

$collection= [1,2,3];
$limit = 3;
$result = CollectionHumanizer::oxford($collection, $limit, 'ru');

The expected result:
1, 2, 3

The result I got is exception bellow:

[Symfony\Component\Translation\Exception\InvalidArgumentException] 
Unable to choose a translation for &quot;{1} %list% и ещё 1|[2,Inf] %list% и ещё %count%&quot; with locale &quot;ru&quot; for value &quot;0&quot;. Double check that this translation has the correct plural options (e.g. &quot;There is one apple|There are %count% apples&quot;).

So if count of items in $collection is equal or less than $limit, exception will be throwed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.