How to verify that vsprintf has the correct number of arguments before running

I am trying to use vsprintf () to output a formatted string, but I need to check that I have the correct number of arguments before running it to prevent the "Too few arguments" errors.

Essentially, I think I need a regex to count the number of type specifiers, but I'm pretty useless when it comes to regex, and I couldn't finance it, so I thought I'd give SO go go, :)

If you can’t come up with a better way, this method will match what I want.

function __insertVars($string, $vars = array()) {

    $regex = '';
    $total_req = count(preg_match($regex, $string));

    if($total_req === count($vars)) {
        return vsprintf($string, $vars);
    }

}

Please tell me if you can come up with an easier way.

+3
2

, - , .

, , preg_match_all():

%[-+]?(?:[ 0]|['].)?[a]?\d*(?:[.]\d*)?[%bcdeEufFgGosxX]

sprintf() . PHP 4.0.6+/5.


EDIT - :

%[-+]?(?:[ 0]|'.)?a?\d*(?:\.\d*)?[%bcdeEufFgGosxX]

, func_get_args() func_num_args() .


: - positional/swapping ( ):

function validatePrintf($format, $arguments)
{
    if (preg_match_all("~%(?:(\d+)[$])?[-+]?(?:[ 0]|['].)?(?:[-]?\d+)?(?:[.]\d+)?[%bcdeEufFgGosxX]~", $format, $expected) > 0)
    {
        $expected = intval(max($expected[1], count(array_unique($expected[1]))));

        if (count((array) $arguments) >= $expected)
        {
            return true;
        }
    }

    return false;
}

var_dump(validatePrintf('The %2$s contains %1$d monkeys', array(5, 'tree')));
+4

.

$countArgs ( ) $countVariables ( $format like% s). :

$object->format('Hello, %s!', ['Foo']); // $countArgs = 1, $countVariables = 1;

: , Foo!

$object->format('Hello, %s! How are you, %s?', ['Bar']); // $countArgs = 1, $countVariables = 2;

: .

:

public static function format($format, array $args)
{
    $pattern = "~%(?:(\d+)[$])?[-+]?(?:[ 0]|['].)?(?:[-]?\d+)?(?:[.]\d+)?[%bcdeEufFgGosxX]~";

    $countArgs = count($args);
    preg_match_all($pattern, $format, $expected);
    $countVariables = isset($expected[0]) ? count($expected[0]) : 0;

    if ($countArgs !== $countVariables) {
        throw new \Exception('The number of arguments in the string does not match the number of arguments in a template.');
    } else {
        return $countArgs > 1 ? vsprintf($format, $args) : sprintf($format, reset($args));
    }
}
0

Source: https://habr.com/ru/post/1728246/


All Articles