0

我有字符串,例如:

bool dxDrawImage float posX, float posY, float width, float height, mixed image , float rotation = 0, float rotationCenterOffsetX = 0, float rotationCenterOffsetY = 0, int color = white, bool postGUI = false
bool dxUpdateScreenSource element screenSource, bool resampleNow =false

我需要从中获取零件,例如:

bool dxDrawImage
float posX
float posY
...

我写:

preg_match_all("/(bool|float|int)[a-zA-Z0-9\s=]+/", $txt, $ar);

打印_r($ar):

Array ( [0] => Array ( [0] => bool dxDrawImage float posX [1] => float posY [2] => float width [3] => float height [4] => float rotation = 0 [5] => float rotationCenterOffsetX = 0 [6] => float rotationCenterOffsetY = 0 [7] => int color = white [8] => bool postGUI = false ) [1] => Array ( [0] => bool [1] => float [2] => float [3] => float [4] => float [5] => float [6] => float [7] => int [8] => bool ) )

为什么这个正则表达式捕获bool dxDrawImage float posX而不是

bool dxDrawImage
float posX

如何解决这个问题?

4

4 回答 4

1

您可以在变量名中禁止空格:

preg_match_all("/(bool|float|int)\s+[a-zA-Z0-9=]+/", $txt, $ar);

如果你将使用:

preg_match_all("/(bool|float|int)\s+[a-zA-Z0-9]+(\s+=\s+[chars,possible for value]+)?/", $txt, $ar);
于 2012-07-21T13:00:10.203 回答
1
preg_match_all("/(\b(?:bool|float|int|element)\s+.*?)(?=\b(?:bool|float|int|element|[,;\n\r]|$))/", $txt, $ar); 
print_r($ar[1]);
于 2012-07-21T13:09:49.647 回答
0

也许您可以使用不贪婪的标志。

preg_match_all("/(bool|float|int)[a-zA-Z0-9\s=]+/U", $txt, $ar);
于 2012-07-21T13:02:14.570 回答
0

将一个变量与另一个变量分隔的部分在您的字符串中有点不清楚。这使得将它们彼此分开有点困难。但是,您仍然可以相对简单地编写模式,因为它发生:

((?:bool|float|mixed|int|element) [a-zA-Z]+(?: = ?[a-z0-9]+)?)(?:\s?,\s?|\s|$)
|^-------- variable type -------^     |    ^--- optional ---^|^-- delimiter -^
|                                   name                     |
|                                                            |
`------------------ the interesting part --------------------´

这种模式适用于preg_match_all

$pattern = '(((?:bool|float|mixed|int|element) [a-zA-Z]+(?: = ?[a-z0-9]+)?)(?:\s?,\s?|\s|$))';
$variables = array();
if ($r = preg_match_all($pattern, $subject, $matches)) {
    $variables = $matches[1];
}
print_r($variables);

输出:

Array
(
    [0] => bool dxDrawImage
    [1] => float posX
    [2] => float posY
    [3] => float width
    [4] => float height
    [5] => mixed image
    [6] => float rotation = 0
    [7] => float rotationCenterOffsetX = 0
    [8] => float rotationCenterOffsetY = 0
    [9] => int color = white
    [10] => bool postGUI = false
    [11] => bool dxUpdateScreenSource
    [12] => element screenSource
    [13] => bool resampleNow =false
)

另一种选择是仅使用分隔符并拆分字符串。然而,在分隔符之后是一个变量类型加空格(前瞻):

$pattern = '((?:\s?,\s?|\s)(?=(?:bool|float|mixed|int|element)))';
$variables = preg_split($pattern, $subject);
print_r($variables);

它为您提供与上述相同的结果。

于 2012-07-21T15:59:39.407 回答