yuanqing / extract
Sugar for getting data out of strings in PHP.
Requires
- php: >=5.3
This package is not auto-updated.
Last update: 2020-01-20 03:37:41 UTC
README
Regex sugar for getting data out of strings:
use yuanqing\Extract\Extract; $e = new Extract('{{ foo.bar }}, {{ foo.baz }}!'); $e->extract('Hello, World!'); #=> ['foo' => ['bar' => 'Hello', 'baz' => 'World']]
Boom.
Usage
-
If the given string does not match the required format,
null
is returned. -
Each capturing group is enclosed in double braces. Within said braces, we have:
- The name of the capturing group
- (optional) A character length
- (optional) A type specifier
-
A capturing group can be an arbitrary string (
s
):$e = new Extract('{{ foo: s }}, {{ bar: s }}!'); $e->extract('Hello, World!'); #=> ['foo' => 'Hello', 'bar' => 'World'] $e->extract('Hola, World!'); #=> ['foo' => 'Hola', 'bar' => 'World'] $e = new Extract('{{ foo: 5s }}, {{ bar: 5s }}!'); $e->extract('Hello, World!'); #=> ['foo' => 'Hello', 'bar' => 'World'] $e->extract('Hola, World!'); #=> null
-
...or an integer (
d
):$e = new Extract('{{ day: d }}-{{ month: d }}-{{ year: d }}'); $e->extract('31-12-2014'); #=> ['day' => 31, 'month' => 12, 'year' => 2014] $e->extract('31-12-14'); #=> ['day' => 31, 'month' => 12, 'year' => 14] $e->extract('31-Dec-2014'); #=> null $e = new Extract('{{ day: 2d }}-{{ month: 2d }}-{{ year: 4d }}'); $e->extract('31-12-2014'); #=> ['day' => 31, 'month' => 12, 'year' => 2014] $e->extract('31-12-14'); #=> null
-
...or a float (
f
):$e = new Extract('{{ tau: f }}, {{ pi: f }}'); $e->extract('6.28, 3.14'); #=> ['tau' => 6.28, 'pi' => 3.14] $e->extract('tau, pi'); #=> null $e = new Extract('{{ tau: 1.f }}, {{ pi: 1.f }}'); $e->extract('6.28, 3.14'); #=> ['tau' => 6.28, 'pi' => 3.14] $e->extract('06.28, 03.14'); #=> null $e = new Extract('{{ tau: .2f }}, {{ pi: .2f }}'); $e->extract('6.28, 3.14'); #=> ['tau' => 6.28, 'pi' => 3.14] $e->extract('6.283, 3.142'); #=> null $e = new Extract('{{ tau: 1.2f }}, {{ pi: 1.2f }}'); $e->extract('6.28, 3.14'); #=> ['tau' => 6.28, 'pi' => 3.14] $e->extract('6.3, 3.1'); #=> null
All the examples in this README are in the examples.php file. You can also find more usage examples in the tests.
Requirements
Extract.php requires at least PHP 5.3, or HHVM.
Installation
Install with Composer
-
Install Composer.
-
Install the Extract.php Composer package:
$ composer require yuanqing/extract ~0.1
-
In your PHP, require the Composer autoloader:
require_once __DIR__ . '/vendor/autoload.php';
Install manually
-
Clone this repository:
$ git clone https://github.com/yuanqing/extract
Or just grab the zip.
-
In your PHP, require Extract.php:
require_once __DIR__ . '/src/Extract.php';
Testing
You need PHPUnit to run the tests:
$ git clone https://github.com/yuanqing/extract
$ cd extract
$ phpunit
License
MIT license