以下代碼不會給我預期的結果。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可以作爲參考來處理。不知道,但...
順便說,'$匹配=陣列();'這種說法是不必要的。當未定義的變量通過引用傳遞時,PHP會自動將它初始化爲NULL,而不會出現任何錯誤。 – mpyw 2013-05-12 11:30:29
不知道你在做什麼,但我會認爲這段代碼從不執行,並且輸出來自別的東西,你也不需要指定'$ matches = array();'(你可以把它刪除) – HamZa 2013-05-12 11:30:35
初始化匹配變量是一種安全措施。腳本中可能有其他匹配變量。 – reggie 2013-05-12 11:34:30