2013-01-22 42 views
0

我想驗證一個字符串(PHP &正則表達式),我想選擇一個成功驗證,但B選項不都驗證:正則表達式驗證包括HTML編碼字符

a) fsadgfsd!^[email protected]<>&lt; 
      OR 
    fsadgfsd!^[email protected]<>&gt;&lt; 


b) fsadgfsd!^[email protected]<>&; 
      OR 
    fsadgfsd!^[email protected]<>;&&; 

到目前爲止,我有這樣的:

/^[a-zA-Z0-9 \!\^\_\@\<\>-]+$/ 

這是驗證了我的一切,除了爲<和>的HTML編碼子和我打這個階段它磚牆,任何幫助,不勝感激。

基本上,除了與我的特殊字符匹配的現有正則表達式,我還需要能夠匹配<或>的確切子字符串,但不匹配&或;性格獨立。

由於代碼限制我使用,我不是在現在的位置,以便能夠要麼驗證之前,對數據進行解碼...

+0

這兩個選項不會驗證,因爲它們包含符號和分號 – Ifthikhan

+0

這就是我想我是墜落短,我能找到沒有辦法驗證& and ;字符,只有當他們是<或> –

回答

1
$regex = '/^[\w !\^@<>-]+$/'; 


$string = 'fsadgfsd!^[email protected]<>&gt;&lt;'; 
$string = html_entity_decode($string); 
if (preg_match($regex, $string)) 
    echo 'ok'; 
// echo ok 


$string = 'fsadgfsd!^[email protected]<>;&&;'; 
$string = html_entity_decode($string); 
if (preg_match($regex, $string)) 
    echo 'ok'; 
// echo nothing 

\ w是一個快捷方式[A-ZA-Z0-9_]

編輯:無html_entity_decode

$regex = '/^([\w !\^@<>-]*(&[glt]+;)*)+$/'; 


$string = 'fsadgfsd!^[email protected]<>&gt;&lt;'; 
if (preg_match($regex, $string)) 
    echo 'ok'; 
// echo ok 
echo '-------------'; 

$string = 'fsadgfsd!^[email protected]<>;&&;'; 
if (preg_match($regex, $string)) 
    echo 'ok'; 
// echo nothing 
+0

的一部分時,嘿路易斯,也許我的問題不像描述的那樣。我需要能夠匹配<或>的確切子字符串,但它們本身不匹配& or ;字符。我將更新問題以反映此 –

+0

+1指出\ w快捷方式,謝謝 –

+1

我編輯了我的答案,我理解你的問題嗎? –