2011-07-29 97 views
1

我想在IF語句中使用preg_match並返回false如果一個字符串包含一些不允許的模板函數。php正則表達式preg_match只允許某些關鍵字

下面是一些例子模板功能允許:

{function="nl2br($value.field_30)"} 
{function="substr($value.field_30,0,250)"} 
{function="addslashes($listing.photo.image_title)"} 
{function="urlencode($listing.link)"} 
{function="AdZone(1)"} 

這些都與HTML等

混在現在,我想這個說法的preg_match返回true,如果正則表達式的代碼格式相匹配,但沒不包含允許的功能關鍵字之一:

if (preg_match('(({function=)(.+?)(nl2br|substr|addslashes|urlencode|AdZone)(.+?)\})',$string)) { 
    // found a function not allowed 
} else { 
    // string contains only allowed functions or doesn't contain functions at all 
} 

有沒有人知道如何做到這一點?

+2

不知道正則表達式是最好的工具。也許他們可以結合舊的老式標記器和解析器: - ?不過,這個問題很好,不管這個功能的潛在風險如何:) –

+0

我打算這麼做,但爲了保持代碼清潔,我想我會先問這裏一個簡單的if語句解決方案。 – Joe

回答

0

不太清楚你想要什麼在這裏,但如果我作出這樣的匹配的單詞(或函數名視情況而定)的列表中的正則表達式,我願意做財產以後像

// add/remove allowed stuff here 
$allowed = array('nl2br', 'substr', 'addslashes'); 

// make the array into a branching pattern 
$allowed_pattern = implode('|', $allowed); 

// the entire regexp (a little stricter than yours)  
$pattern = "/\{function=\"($allowed_pattern)\((.*?)\)\"\}/"; 

if(preg_match($pattern, $string, $matches)) { 
    # string DOES contain an allowed function 
    # The $matches things is optional, but nice. $matches[1] will be the function name, and 
    # $matches[2] will be the arguments string. Of course, you could just do a 
    # preg_replace_callback() on everything instead using the same pattern... 
} else { 
    # No allowed functions found 
} 

$allowed數組可以更容易地添加/刪除允許的函數名稱,而正則表達式對花括號,引號和一般語法更嚴格,這可能是一個好主意。

但首先,翻轉if..else分支,或使用!preg_match是爲了匹配字符串中的東西,而不是用於匹配不在那裏的東西。所以你不能真正得到它返回true的東西

儘管如此,正如阿爾瓦羅提到,正則表達式可能並不去了解這一點的最好方式,這是非常危險的有函數暴露出來,不管代碼的其他部分如何。如果你只需要匹配單詞,它應該可以正常工作,但是因爲它是帶有任意參數的函數調用......嗯。我真的不能推薦它:)

編輯:第一次,我用preg_quote在內爆的字符串,但這當然只是逃脫管道字符,然後模式將無法正常工作。所以跳過preg_quote,但當時只是要確保功能名稱不包含任何可能搞砸最終模式(例如,通過preg_quote之前運行的每個函數名爆數組)

+0

這將工作!謝謝! – Joe