2014-01-21 30 views
0

我想使用preg_replace_callback填寫導入文檔中的變量(我控制),基於this answer,但它不起作用。據我所知,回調從不被調用,這意味着正則表達式永遠不會被匹配。簡單的正則表達式不工作使用preg_replace_callback()

doc.html文件的裸機內容:

<p>test {$test} $test test</p> 

的PHP:

$test = "ham"; 
$allVars = get_defined_vars(); 

$filename = "/path/to/doc.html"; 
$html = file_get_contents($filename); 
$html = preg_replace_callback("/\$[a-zA-Z_][a-zA-Z0-9_]*/", "find_replacements", $html); 

echo($html); 
exit(); 

// replace callback function 
function find_replacements($match) { 
    global $allVars; 
    if (array_key_exists($match[0], $allVars)) 
     return $allVars[$match[0]]; 
    else 
     return $match[0]; 
} 

輸出爲<p>test {$test} $test test</p>,但我期待<p>test {ham} ham test</p>

+0

我不會使用'$',因爲PHP已經將它用於插值,它可能導致令人討厭的錯誤。嘗試使用不同的字符,如'test {#test} #test test' – elclanrs

+1

如果您使用'$',請嘗試將您的正則表達式放在單引號中。 – elclanrs

+0

就是這樣 - 在我的正則表達式中使用單引號。你能寫一個答案來解釋爲什麼嗎? – Blazemonger

回答

1

首先,美元符號在正則表達式正在被插值的PHP,因爲正則表達式在雙引號。把單引號括起來的是:

$html = preg_replace_callback('/\$[a-zA-Z_][a-zA-Z0-9_]*/', "find_replacements", $html); 

其次,發送到您的回調值包括美元符號,而美元符號是不存在的$allVars陣中,所以你必須手動剝離其關閉:

function find_replacements($match) { 
    global $allVars; 
    $match[0] = substr($match[0],1); 
    if (array_key_exists($match[0], $allVars)) 
     return $allVars[$match[0]]; 
    else 
     return $match[0]; 
} 

製作這些修改,我能夠接收這個輸出:

測試{火腿}火腿測試

+0

我在提交問題後發現了第二個問題,並使用'$ allVars [$ match [1]]'修復了問題,並在我的正則表達式中添加了括號:''/ \ $([a-zA-Z _] [a- zA-Z0-9 _] *)/'' - 感謝您的替代解決方案,但! – Blazemonger

相關問題