考虑sprintf
创建的典型结构
$pattern = "%1$s-%2$s|%3$s";
$str = sprintf($pattern, $a, $b, $c);
现在我们有一个字符串test-fore|here
我们如何使用 sprintf
模式来解析后一个字符串,以获取$a
,$b
和$c
的值。
答案 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');