1

我尝试使用 php 解析字符串sscanf()

$n = sscanf($line, "%s.%s.%s=%s", $ws, $layer, $perm, $role);
echo $ws." - ".$layer." - ".$perm." - ".$role."\n";

并获得输出:

*.*.r=* -  -  -
topp.*.a=jdbs_watcher -  -  -

输入示例:

 *.*.r=*
 topp.*.a=jdbs_watcher

我希望看到第二个字符串:

topp - * - a - jdbc_watcher

为什么将整个字符串放入$ws变量中?

4

4 回答 4

3

%s将在空格分隔符之前匹配尽可能多的字符。您可以使用preg_match得到类似的东西:

preg_match("/(.*)\.(.*)\.(.*)=(.*)/", $line, $matches);
array_shift($matches);
list($ws, $layer, $perm, $role) = $matches;

演示

于 2013-09-17T06:36:05.730 回答
3

用于^避免过于贪婪:

<?php
$line = 'topp.*.a=jdbs_watcher';
$n = sscanf($line, "%[^.].%[^.].%[^=]=%s", $ws, $layer, $perm, $role);
echo $ws." - ".$layer." - ".$perm." - ".$role."\n";
于 2013-09-17T06:45:08.373 回答
2

sscanf()不是字符串解析器。它是一个格式化输入扫描器,用于使用 C 样式语法将格式化输入分配给变量。你想完成的事情可以用explode().

//Scan input
$n = sscanf($line, "%s", $input);

//Parse by .
$parsed = explode(".", $input);
//Parse by =
$parsed[2] = explode("=", $parsed[2]);

//Create bindings
$ws = $parsed[0];
$layer = $parsed[1];
$perm = $parsed[2][0];
$role = $parsed[2][1];

//Echo
echo $ws." - ".$layer." - ".$perm." - ".$role."\n";
于 2013-09-17T06:36:47.930 回答
2

好吧,之前在php.net上发现了这种行为。

作为一种解决方法,您可以使用以下方法:

<?php
header('Content-Type: text/plain; charset=utf-8');

$line = 'topp.*.a=jdbs_watcher';

list($ws, $layer, $perm) = explode('.', $line);
list($perm, $role) = explode('=', $perm); 

echo $ws." - ".$layer." - ".$perm." - ".$role."\n";
?>

结果:

topp - * - a - jdbs_watcher
于 2013-09-17T06:46:23.527 回答