A package to replace words in a text with values from a array. Also supports aliases and excluded properties.
You can install the package via composer:
composer require singlequote/laravel-text-parser
Parser::text('Hello [who]')->values(['who' => 'world'])->parse(); // Hello world
Parser::text('Hello {who}')->values(['who' => 'world'])->tags(['{', '}'])->parse(); // Hello world
Parser::text('Hello [who]')->values(['who' => 'world'])->exclude(['who'])->parse(); // Hello [who]
Parser::text('Hello [what]')->values(['who' => 'world'])->aliases(['what' => 'who'])->parse(); // Hello world
$values = [
'user' => [
'name' => [
'first_name' => 'Foo',
'last_name' => 'Bar'
],
'email' => '[email protected]'
]
];
$input = "[user.name.first_name][user.name.last_name] - [user.email]";
$result = Parser::text($input)->values($values)->parse();
will generate FooBar - [email protected]
All methods can be chained together like text()->values()->aliases()
and can be in any order.
But you always have to start with the text()
function.
This sets the string you want to parse
$parser = Parser::text('string')
This sets the values to use while parsing. Must be a array
$parser->values([]);
Tags are the characters around the keys you want to parse. Default [
and ]
$parser->tags(['{','}']);
Sets the keys which are excluded from parsing
$parser->exclude(['key', 'key2']);
Sets the aliases. Aliases can be used to map a value to a different name.
So for example you can set the aliases to ['name' => 'username']
to map username
to name
$parser->exclude(['alias', 'value key']);
Parses the text and returns the parsed string
$parser->exclude(['alias', 'value key']);
composer test
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.