2013-05-12 104 views
-1

以下代码不会给我预期的结果。Preg_match与PHP中的引用变量

if (isset($newpost['message'])) 
{ 
    $matches = array(); 
    preg_match_all("~\[QUOTE\=.*;(\d+)\]~isU", $newpost['message'], $matches); 

    var_dump($matches); 
    die(); 
} 

$ matches应该包含匹配的结果。 但是,$匹配总是等于整个$ newpost数组(不仅是消息部分)。 上面的结果看起来是这样的:

array(22) { ["message"]=> string(17) "testing123..." ["title"]=> &string(0) "" ["iconid"]=> &int(0) ["parseurl"]=> bool(true) ["signature"]=> &int(1) ["preview"]=> &string(0) "" ["disablesmilies"]=> &int(0) ["rating"]=> &int(0) ["username"]=> &string(0) "" ["folderid"]=> &int(0) ["quickreply"]=> &int(0) ["poststarttime"]=> &int(1368357609) ["posthash"]=> &string(32) "4d513f4123f780c6b10739e3a5dd0fb6" ["humanverify"]=> &array(0) { } ["stickunstick"]=> &int(0) ["openclose"]=> &int(0) ["ajaxqrfailed"]=> int(0) ["emailupdate"]=> &int(9999) ["enablesmilies"]=> int(1) ["podcastsize"]=> int(0) ["visible"]=> int(1) ["postid"]=> int(1771567) } 

我想这是因为$ newpost可以作为参考来处理。不知道,但...

+0

顺便说,'$匹配=阵列();'这种说法是不必要的。当未定义的变量通过引用传递时,PHP会自动将它初始化为NULL,而不会出现任何错误。 – mpyw 2013-05-12 11:30:29

+0

不知道你在做什么,但我会认为这段代码从不执行,并且输出来自别的东西,你也不需要指定'$ matches = array();'(你可以把它删除) – HamZa 2013-05-12 11:30:35

+0

初始化匹配变量是一种安全措施。脚本中可能有其他匹配变量。 – reggie 2013-05-12 11:34:30

回答

0

输出来自其他地方的脚本...

+0

大声笑**像老板** – HamZa 2013-05-12 11:43:49

1

我测试了Ideone这个代码,它果然奏效。

代码:

<?php 

$text = <<<EOD 
abc [QUOTE=ABC;123] 
def [Quote=DEF;456] 
ghi 
EOD; 

$newpost = array('message' => $text); 

if (isset($newpost['message'])) { 
    preg_match_all('/\\[QUOTE=[^;]++;(\\d++)\\]/i', $newpost['message'], $matches); 
    var_dump($matches); 
} 

结果:

array(2) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(15) "[QUOTE=ABC;123]" 
    [1]=> 
    string(15) "[Quote=DEF;456]" 
    } 
    [1]=> 
    array(2) { 
    [0]=> 
    string(3) "123" 
    [1]=> 
    string(3) "456" 
    } 
}