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.
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():Based upon
sprintf()documentation. Should be compatible with PHP 4.0.6+ / 5.EDIT – A slightly more compact version:
Also, take advantage of the
func_get_args()andfunc_num_args()functions in your code.EDIT: – Updated to support positional/swapping arguments (not tested):