如何在PHP中解析sprintf字符串

时间:2013-05-10 11:42:05

标签: php string parsing printf

考虑sprintf创建的典型结构

$pattern = "%1$s-%2$s|%3$s";
$str = sprintf($pattern, $a, $b, $c);

现在我们有一个字符串test-fore|here

我们如何使用 sprintf模式来解析后一个字符串,以获取$a$b$c的值。

1 个答案:

答案 0 :(得分:0)

尝试使用正则表达式:

function sscanfAlt($format, $str){

  // split string by %s, %d, %2$s etc.
  // note that this regex doesn't handle some identifiers
  // like precision or padding
  $parts = preg_split('/(%(?:\d\$)?[bcdeEufFgGosxX])/', $format, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

  // odd entries = format directives; even entries = normal text
  foreach($parts as $idx => &$value)
    $value = ($idx & 1) ? preg_quote($value, '/') : '(.*)';

  // rebuild as regex
  preg_match('/' . implode('', $parts) . '/', $str, $matches);
  array_shift($matches);
  return $matches;
}  

使用类似:

$values = sscanfAlt('%1$s-%2$s|%3$s', 'test-fore|here');