views:

90

answers:

1

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.

+2  A: 

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.

Alix Axel
Works perfectly, thank you.
rich97
No problem rich97.
Alix Axel