lukaswhite/token-strings
Composer 安装命令:
composer create-project lukaswhite/token-strings
包简介
A library for replacing tokens in strings
README 文档
README
This simple library allows you to create a string that includes tokens, for example:
Dear [[FORENAME]] [[SURNAME]],
Then provide values for the tokens at runtime:
[ 'FORENAME' => 'Joe', 'SURNAME' => 'Bloggs', ]
And run a token substitution:
Dear Joe Bloggs,
It's useful for things like page titles, notification templates, mail merge and more.
Installation
Install using Composer:
composer require lukaswhite/token-strings
Basic Usage
Create an instance:
use Lukaswhite\TokenStrings\Substitutor( ); $substitutor = new Substitutor( 'Dear [[FORENAME]] [[SURNAME]],', [ 'forename' => 'Joe', 'surname' => 'Bloggs', ] );
Then run it:
$replaced = $substitutor->run( ); // or $replaced = ( string ) $substitutor;
Advanced Usage
You can modify the content of the template at any time:
$substitutor->setContent( 'Hey [[FORENAME]]' );
To add tokens:
$substitutor->addToken( 'age', 43 );
To clear the tokens:
$substitutor->clearTokens( );
If you'd prefer differrnt markup for the tokens:
$substitutor->setOpeningTag( '{{' )->setClosingTag( '}}' );
Since the closing tag in the example above is simply the reverse of the opening tag, you can simply do this:
$substitutor->setOpeningTag( '{{' );
In addition to passing strings as token values, you can also pass an object, provided it implements the magic __toString() method:
class Person { private $forename; private $surname; public function __construct( $forename, $surname ) { $this->forename = $forename; $this->surname = $surname; } public function __toString( ) { return sprintf( '%s %s', $this->forename, $this->surname ); } } $substitutor = new Substitutor( 'Dear [[NAME]],', [ 'NAME' => new Person( 'Joe', 'Bloggs' ), ] );
To get a list of the available tokens, call getAvailableTokens().
The validate() method checks that the string you provide does not contain any tokens for which you haven't provided values.
Notes
- Tokens must only contain letters, numbers, dashes and underscores
- By convention tokens are uppercase, but if you provide an array with the tokens in lowercase, it'll convert them for you
- If the string contains tokens that you have not provide values for, it will replace them with empty strings
统计信息
- 总下载量: 15
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-10-23