Git Product home page Git Product logo

php_rutils's Introduction

PHP RUtils

RUtils is a Russian-specific string utils (transliteration, numeral is words, russian dates, typography) for PHP. This is a port of the Python Pytils to PHP.

See additional docs and examples in doc subdir.

Library is published on the Composer: https://packagist.org/packages/andre_487/php_rutils


RUtils — утилиты для работы c текстом на русском языке (транслитерация, числительные словами, русские даты, простая типографика) для языка PHP. RUtils — порт утилит Pytils на PHP.

Документацию и примеры смотрите в каталоге doc.

Библиотека доступна через Composer: https://packagist.org/packages/andre_487/php_rutils


Буду рад принять помощь по проекту в виде советов, баг-репортов и pull-реквестов.

Хочу сказать большое спасибо всем людям, внесшим свой вклад в улучшение проекта.


Basic usage

Modules of PHP RUtils:

  • Numeral - Plural forms and in-word representation for numerals
  • Dt - Russian dates without locales and other dates handling
  • Translit - Simple transliteration
  • Typo - Basic russian typography

Numeral

Choosing the word form depending of a number:

$variants = array(
    'гвоздь', //1
    'гвоздя', //2
    'гвоздей' //5
);
echo $amount, ' ', RUtils::numeral()->choosePlural(15, $variants);
//Result: 15 гвоздей

echo RUtils::numeral()->getPlural(2, $variants);
//Result: 2 гвоздя

Choosing the word form and print number in words:

echo RUtils::numeral()->sumString(1234, RUtils::MALE, $variants);
//Result: одна тысяча двести тридцать четыре гвоздя

Print number in words:

$numeral = RUtils::numeral();
echo $numeral->getInWordsInt(100);
//Result: сто

echo $numeral->getInWordsFloat(100.025);
//Result: сто целых двадцать пять тысячных

echo $numeral->getInWords(100.0);
//Result: сто

Print money (RUB):

echo RUtils::numeral()->getRubles(100.25);
//Result: сто рублей двадцать пять копеек

Dt

Today date: \php_rutils\struct\TimeParams - params structure, may be passed as array

$params = new TimeParams();
$params->date = null; //default value, 'now'
$params->format = 'сегодня d F Y года';
$params->monthInflected = true;
echo RUtils::dt()->ruStrFTime($params);
//Result: сегодня 22 октября 2013 года

Historical date:

$params = array(
    'date' => '09-05-1945',
    'format' => 'l d F Y была одержана победа над немецко-фашистскими захватчиками',
    'monthInflected' => true,
    'preposition' => true,
);
echo RUtils::dt()->ruStrFTime($params);
//Result: в среду 9 мая 1945 была одержана победа над немецко-фашистскими захватчиками

Time interval to fixed date:

$toTime = new \DateTime('05-06-1945'); //Unix timestamp and string also available
echo RUtils::dt()->distanceOfTimeInWords($toTime), PHP_EOL;
//Result: 68 лет назад

$toTime = strtotime('05-06-1945');
$fromTime = null; //now
$accuracy = RUtils::ACCURACY_MINUTE; //years, months, days, hours, minutes
echo RUtils::dt()->distanceOfTimeInWords($toTime, $fromTime, $accuracy), PHP_EOL;
//Result: 68 лет, 4 месяца, 21 день, 19 часов, 12 минут назад

Time interval from fixed date to fixed date:

$fromTime = '1988-01-01 11:40';
$toTime = '2088-01-01 12:35';
$accuracy = RUtils::ACCURACY_MINUTE; //years, months, days, hours, minutes
echo RUtils::dt()->distanceOfTimeInWords($toTime, $fromTime, $accuracy), PHP_EOL;
//Result: через 100 лет, 55 минут

Age:

$birthDate = strtotime('today - 25 years');
echo RUtils::dt()->getAge($birthDate);
//Result: 25

Translit

//Translify
echo RUtils::translit()->translify('Муха - это маленькая птичка');
//Result: Muxa - e`to malen`kaya ptichka

//Detranslify
echo RUtils::translit()->detranslify("Muxa - e`to malen`kaya ptichka");
//Result: Муха - это маленькая птичка

//Prepare to use in URLs or file paths
echo RUtils::translit()->slugify('Муха — это маленькая птичка');
//Result: muha-eto-malenkaya-ptichka

Typo

$text = <<<TEXT
...Когда В. И. Пупкин увидел в газете ( это была "Сермяжная правда" № 45) рубрику Weather Forecast (r),
он не поверил своим глазам - температуру обещали +-451F.
TEXT;

//Standard rules
echo RUtils::typo()->typography($text);
/**
 * Result:
 * ...Когда В. И. Пупкин увидел в газете (это была «Сермяжная правда» №45) рубрику Weather Forecast®,
 * он не поверил своим глазам — температуру обещали ±451°F.
 */


//Extended rules
echo RUtils::typo()->typography($text, TypoRules::$EXTENDED_RULES);
/**
 * Result:
 * …Когда В. И. Пупкин увидел в газете (это была «Сермяжная правда» №45) рубрику Weather Forecast®,
 * он не поверил своим глазам — температуру обещали ±451 °F.
 */

//Custom rules
echo RUtils::typo()->typography($text, array(TypoRules::DASHES, TypoRules::CLEAN_SPACES));
/**
 * Result:
 * ...Когда В. И. Пупкин увидел в газете (это была "Сермяжная правда" № 45) рубрику Weather Forecast (r),
 * он не поверил своим глазам — температуру обещали +-451F.
 */

php_rutils's People

Contributors

andre487 avatar boldyrev avatar githubjeka avatar walik91 avatar

Watchers

 avatar  avatar

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.