rich97 rich97 - 1 year ago 60
PHP Question

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

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

In essence I think what I need is a regex to count the number of type specifiers, but I'm pretty useless when it comes to regex and I couldn't fund it anywhere so I thought I'd give SO a go. :)

Unless you can think of a better way this method is along the lines of 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 think of a simpler way.

Answer Source

I think your solution is the only way to more or less reliably tell how many arguments are in the string.

Here is the regular expression I came up with, use it with preg_match_all():

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

Based upon sprintf() documentation. Should be compatible with PHP 4.0.6+ / 5.

EDIT - A slightly more compact version:

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

Also, take advantage of the func_get_args() and func_num_args() functions in your code.

EDIT: - Updated to support positional/swapping arguments (not tested):

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')));