PHP 字符串解析通用函数

字符串解析通用函数

<?php

function extract_values(
    $string,
    $pattern,
    $lowercase = false,
    $whitespace = null,
    $strip_values = false,
    $delimiters = ['{', '}']
) {
    // 处理大小写转换
    if ($lowercase) {
        $string = strtolower($string);
    }

    // 验证分隔符
    if (!is_array($delimiters) || count($delimiters) != 2) {
        return [];
    }
    list($start_delim, $end_delim) = $delimiters;

    // 处理空白字符
    if ($whitespace !== null) {
        if (!is_int($whitespace) || $whitespace < 0) {
            return [];
        }

        if ($whitespace == 0) {
            $string = preg_replace('/\s+/', '', $string);
        } else {
            $string = preg_replace('/\s{'.($whitespace + 1).',}/', ' ', $string);
        }
    }

    // 构建正则表达式模式
    $splitter = '/('.preg_quote($start_delim).'\w+'.preg_quote($end_delim).')/';
    $extracter = '/'.preg_quote($start_delim).'(\w+)'.preg_quote($end_delim).'/';

    // 分割模式
    $parts = preg_split($splitter, $pattern, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    $regex_parts = [];
    foreach ($parts as $p) {
        if (preg_match($extracter, $p, $matches)) {
            $name = $matches[1];
            $regex_parts[] = "(?P<$name>.+?)";
        } else {
            $regex_parts[] = preg_quote($p, '/');
        }
    }

    $expanded_pattern = '/^'.implode('', $regex_parts).'$/';

    // 执行匹配
    if (!preg_match($expanded_pattern, $string, $matches)) {
        return [];
    }

    // 提取结果
    $result = [];
    foreach ($matches as $key => $value) {
        if (!is_int($key)) {
            $result[$key] = $strip_values ? trim($value) : $value;
        }
    }

    return $result;
}

// 测试用例
print_r(extract_values('380-250-80-j', '{width}-{height}-{quality}-{format}'));
print_r(extract_values('/2012/08/12/test.html', '/{year}/{month}/{day}/{title}.html'));
print_r(extract_values('John Doe <john@example.com> (http://example.com)', '{name} <{email}> ({url})'));
print_r(extract_values('from 4th October  to 10th  October', 'from `from` to `to`', false, 1, true, ['`', '`']));
print_r(extract_values('Convert 1500 Grams to Kilograms', 'convert {quantity} {from_unit} to {to_unit}', true));
print_r(extract_values('The time is 4:35pm here at Lima, Peru', 'The time is :time here at :city', false, null, false, [':', '']));

/*
         * 输出
         *
         Array
        (
            [width] => 380
            [height] => 250
            [quality] => 80
            [format] => j
        )
        Array
        (
            [year] => 2012
            [month] => 08
            [day] => 12
            [title] => test
        )
        Array
        (
            [name] => John Doe
            [email] => john@example.com
            [url] => http://example.com
        )
        Array
        (
            [from] => 4th October
            [to] => 10th October
        )
        Array
        (
            [quantity] => 1500
            [from_unit] => grams
            [to_unit] => kilograms
        )
        Array
        (
            [time] => 4:35pm
            [city] => Lima, Peru
        )
         */

?>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容