mistralys / php-sprintf-parser
解析器,用于查找字符串中所有 sprintf 格式占位符并获取相关信息。
1.0.0-beta.1
2021-11-01 16:11 UTC
Requires
- php: >=7.4
- ext-mbstring: *
Requires (Dev)
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-06 16:14:31 UTC
README
基于 PHP 的解析类,可用于查找字符串中所有 sprintf 函数的格式占位符并获取相关信息。
要求
- PHP >= 7.4
安装
简单通过 composer 引入此包
composer require php-sprintf-parser
或手动添加到 composer.json
{ "require":{ "mistralys/php-sprintf-parser": "^1.0" } }
用法
解析包含多个占位符的文本
可以使用 parseString()
函数查找给定字符串中的所有格式占位符。
use function Mistralys\SprintfParser\Functions\parseString; $parser = parseString('The price of product %1$s has been set to %2$.2d EUR.'); $placeholders = $parser->getPlaceholders();
每个占位符实例可以用来访问占位符配置的相关信息,如编号(如有)、精度、宽度等。
解析单个格式字符串
单个占位符格式字符串也可以解析,以直接获取占位符信息。
use function Mistralys\SprintfParser\Functions\parseFormat; $placeholder = parseFormat('%1$.2d');
访问占位符信息
占位符提供了对格式字符串所有单个组件的访问。正如官方 PHP 文档中对于 sprintf 函数的说明,格式原型如下
%[argnum$][flags][width][.precision]specifier
占位符类允许轻松访问这些组件中的每一个。以下是一个有效的格式示例,使用了所有可能选项。
use function Mistralys\SprintfParser\Functions\parseFormat; $placeholder = parseFormat("%1$+-0'*4.3d"); $placeholder->getSpecifier(); // s $placeholder->getNumber(); // 1 $placeholder->getWidth(); // 4 $placeholder->getPrecision(); // 3 $placeholder->getPaddingChar(); // * $placeholder->hasPlusMinusPrefix(); // true $placeholder->hasLeftJustification(); // true $placeholder->hasOnlyZeroLeftPadding(); // true