簡體   English   中英

PHP正則表達式preg_match只允許某些關鍵字

[英]php regex preg_match allow only certain keywords

我正在嘗試在IF語句中使用preg_match,如果字符串包含某些不允許的模板化函數,則返回false。

這是允許的一些示例模板函數:

{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語句在regex與代碼格式匹配但不包含允許的功能關鍵字之一的情況下返回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
}

有誰知道如何做到這一點?

不太確定您要在這里嘗試什么,但是如果我要使正則表達式與單詞列表(或函數名,視情況而定)匹配,我會做些類似的事情

// 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數組使添加/刪除允許的函數名稱更加容易,而regexp對大括號,引號和常規語法更為嚴格,這可能是一個好主意。

但首先,翻轉if..else分支,或使用! preg_match是為了匹配字符串中的內容,而不是匹配不存在的內容。 因此,對於某些存在的內容,您實際上無法使其返回true

但是,正如Álvaro所提到的,正則表達式可能不是解決此問題的最佳方法,並且不管其他代碼如何,暴露這樣的函數都是非常冒險的。 如果您只需要匹配單詞,它應該可以正常工作,但是由於它是帶有任意參數的函數調用……很好。 我真的不能推薦它:)

編輯:第一次,我在插入的字符串上使用了preg_quote ,但是當然只轉義了豎線字符,然后該模式將不起作用。 因此,跳過preg_quote ,但是只要確保函數名稱不包含任何可能弄亂最終模式的內容即可(例如, 插入數組之前通過preg_quote運行每個函數名稱)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM