How to parse a sprintf string in PHP -
consider typical structure created sprintf as
$pattern = "%1$s-%2$s|%3$s"; $str = sprintf($pattern, $a, $b, $c); now have string test-fore|here
how can parse latter string using sprintf pattern values of $a, $b, , $c.
an attempt using regular expressions:
function sscanfalt($format, $str){ // split string %s, %d, %2$s etc. // note regex doesn't handle identifiers // precision or padding $parts = preg_split('/(%(?:\d\$)?[bcdeeuffggosxx])/', $format, -1, preg_split_delim_capture | preg_split_no_empty); // odd entries = format directives; entries = normal text foreach($parts $idx => &$value) $value = ($idx & 1) ? preg_quote($value, '/') : '(.*)'; // rebuild regex preg_match('/' . implode('', $parts) . '/', $str, $matches); array_shift($matches); return $matches; } use like:
$values = sscanfalt('%1$s-%2$s|%3$s', 'test-fore|here');
Comments
Post a Comment