ta-tikoma/

bog-jug

将正则表达式组转换为对象

dev-main 2023-08-18 08:44 UTC

This package is auto-updated.

Last update: 2024-09-18 11:13:29 UTC


README

一个使处理正则表达式组更轻松的工具。将正则表达式组映射到php类,因为数组太糟糕了。

Static Badge Static Badge Static Badge GitHub

安装

composer require ta-tikoma/bog-jug

使用

  • 为正则表达式描述创建一个类。
  • 使用属性定义正则表达式组:使用 #[Group('...')] 定义组主体;使用 #[After]#[Before] 定义外部符号。
  • 如果您需要指示组计数,请使用来自命名空间 BogJug\Attributes\Count 的属性,如 #[ZeroOrOne]#[ZeroOrMore] 等。
  • 最后,您可以通过类属性添加正则表达式标志;例如:#[SingleLine]
  • 现在创建 BogJug 类的实例并使用两种基本方法之一
    • 方法 ->one($regex, $text) 用于查找与正则表达式相等的第一个值;类似:preg_match
    • 方法 ->many($regex, $text) 用于获取所有与正则表达式相等的值;类似:preg_match_all

示例示例

1. 定义描述类。

<?php

declare(strict_types=1);

namespace tests\Data;

use BogJug\Attributes\Flags\SingleLine;
use BogJug\Attributes\Regex\After;
use BogJug\Attributes\Regex\Group;

#[SingleLine]
final class TinWoodman
{
    public function __construct(
        #[Group('head'), After('.*')]
        public readonly string $noggin,
        #[Group('arms'), After('.*')]
        public readonly string $upperLimbs,
        #[Group('legs'), After('.*')]
        public readonly string $lowerLimbs,
        #[Group('body'), After('.*')]
        public readonly string $torso,
        #[Group('heart'), After('.*')]
        public readonly string|null $coeur,
    ) {
    }
}

2. 调用 BogJug 方法。

        $bj = new BogJug();
        $tw = $bj->one(TinWoodman::class, <<<OZ
One of the big trees had been partly chopped through, and standing beside
it, with an uplifted axe in his hands, was a man made entirely of tin. His head
and arms and legs were jointed upon his body, but he stood perfectly motionless, 
as if he could not stir at all.
OZ);
        dump($tw);

3. 获取结果。

^ tests\Data\TinWoodman^ {#427
  +noggin: "head"
  +upperLimbs: "arms"
  +lowerLimbs: "legs"
  +torso: "body"
  +coeur: null
}