angelopereyra / replace
使用自定义标识符替换子串
v1.1.0
2019-03-26 02:37 UTC
Requires (Dev)
- phpunit/phpunit: 8
- psy/psysh: ^0.9.9
README
安装
> composer require angelopereyra/replace
用法
use Replace\Replaceable; ... $url = new Replaceable('https://mysite.{domain}.com');
从上面的例子中,我们可以用两种方式设置 {domain}
子串的值
$url->addLookup('domain', 'local'); // dumping a dictionary $url->setLookup([ 'domain' => 'local' ]);
然后将对象转换为字符串以获取结果
echo (string)$url; // prints "https://mysite.local.com"
修改令牌格式
将字符串作为构造函数的第二个参数传递以自定义令牌的外观
$url = new Replaceable('https://mysite.$$domain.com', '$$++key++'); // ++key++ is the 🔑
在某些情况下,你可能只需传递一个可调用对象
$url = new Replaceable('https://mysite.UwU domain UwU.com', function($key) { return 'UwU ' . $key . ' UwU'; });
为了方便,也暴露了一个静态辅助函数
$lookup = [ 'type' => 'Bearer', 'token' => 'xoxb-83029aurioDnd' ]; Replaceable::parse('Authorization: @type @token', $lookup, '@++key++') // prints "Authorization: Bearer xoxb-83029aurioDnd"
识别令牌
假设你有以下主题字符串
Hello, {name}. You look {adjective} today.
可替换可以根据给定的令牌格式识别令牌。在这种情况下,我们将使用默认格式,即 {++key++}
。
我们可以使用以下用法来识别令牌
$subject = file_get_contents('...'); $sentence = new Replaceable($subject); $sentence->identifyTokens(false); // returns ['name', 'adjective']
要相对于单词边界识别令牌,将第一个参数设置为 true
$sentence->identifyTokens(true); // returns ['adjective']