2

假设你从这个开始:

$mask = "%name% (%user_count%) - %acyr% - %audience%";
$data = [
    '%name%'       => $group['name'],
    '%user_count%' => $group['user_count'],
    '%acyr%'       => $group['acyr'],
    '%audience%'   => $group['audience'],
];
$result = strtr($mask, $data);

扭转这种情况的最佳方法是什么,以便您转换$result为以下定义和填充的变量?(还要记住,顺序$mask可能会改变。)

$name       = '?';
$user_count = '?';
$acyr       = '?';
$audience   = '?';

我尝试过使用preg_split()/list()但我想$mask控制变量的顺序,而不必将其转换为复杂的正则表达式。基本上,我需要一种简单的方法来根据包含占位符的掩码将字符串解析/拆分为多个变量。

4

1 回答 1

0

可以通过更改占位符的顺序或添加新标点来更改掩码,但逻辑足够灵活以生成变量。

PHP 代码演示

<?php
    $mask = "%name% (%user_count%) - %acyr% - %audience%";
    $data = [
        '%name%'       => 'Year 1',
        '%user_count%' => 999,
        '%acyr%'       => 2017,
        '%audience%'   => 'Staff and Students',
    ];
    $result = strtr($mask, $data);

    // Extract unique punctuation used in mask and form pattern for split
    $pattern = '/[' . preg_replace('/[\w\s%]/', '', count_chars($mask, 3)) . ']/';

    // Split, trim, remove blanks and reset array keys
    $variables = array_values(array_filter(array_map('trim', preg_split($pattern, $mask, -1, PREG_SPLIT_NO_EMPTY)), 'strlen'));
    $data      = array_values(array_filter(array_map('trim', preg_split($pattern, $result, -1, PREG_SPLIT_NO_EMPTY)), 'strlen'));

    foreach ($variables as $key => $variable_name) {
        $variable_name = str_replace('%', '', $variable_name);
        // Dynamically create variable
        ${$variable_name} = $data[$key];
    }

    var_dump("\$name: $name");             // Year 1
    var_dump("\$user_count: $user_count"); // 999
    var_dump("\$acyr: $acyr");             // 2017
    var_dump("\$audience: $audience");     // Staff and Students
于 2017-03-14T15:13:21.253 回答