2014-10-18 122 views
0

腳本:「請檢查您的#標籤」PHP中的標籤驗證 - 允許輸入字段爲空?

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > 
    <input type="text" name="hashtag1" /> 
    <input type="text" name="hashtag2" /> 
    <input type="text" name="hashtag3" /> 
    <input type="text" name="hashtag4" /> 

    <input type="submit" name="submit" /> 
</form> 

<?php 

if(isset($_POST['submit'])){ 

    if(isset($_POST['hashtag1'])) { 
     $hashtag1 = $_POST['hashtag1']; 
    } 
    if(isset($_POST['hashtag2'])){ 
     $hashtag2 = $_POST['hashtag2']; 
    } 
    if(isset($_POST['hashtag3'])){ 
     $hashtag3 = $_POST['hashtag3']; 
    } 
    if(isset($_POST['hashtag4'])){ 
     $hashtag4 = $_POST['hashtag4']; 
    } 

    $myarray = array($hashtag1, $hashtag2, $hashtag3, $hashtag4); 

    for($i = 0; $i < count($myarray); $i++){ 

     if(!preg_match('/^(?=.{2,140}$)(#|\x{ff03}){1}([0-9_\p{L}]*[_\p{L}][0-9_\p{L}]*)$/u', $myarray[$i])){ 
      echo "Please check your hashtags!"; 
      exit; 
     } 

    } 

    function array_has_dupes($array) { 
     return count($array) !== count(array_unique($array)); 
    } 

    if(array_has_dupes($myarray) == true){ 
     echo "Please make sure you do not have duplicate hashtags!"; 
     exit; 
    } 

    echo "Hello World!"; 

} 

?> 

當我離開的那些四個輸入字段爲空一個輸入字段,然後我得到印在屏幕上。

我的問題是,如何修改腳本,讓一個或多個輸入字段爲空是允許的?

我使用的是「PHP Twitter的#標籤驗證的正則表達式」從GitHub:link

回答

2

使用一個變量保持一個有效的主題標籤的軌道,把它定義爲false你的循環之前。如果您找到了有效的標籤,請跳出您的循環並將您的變量設置爲true

你的循環後,檢查變量,如果它仍然是假的,顯示你的錯誤並退出:

$atLeastOne = false; 
for($i = 0; $i < count($myarray); $i++){ 
    if(preg_match('/^(?=.{2,140}$)(#|\x{ff03}){1}([0-9_\p{L}]*[_\p{L}][0-9_\p{L}]*)$/u', $myarray[$i])){ 
     $atLeastOne = true; 
     break; 
    } 
} 
if(!$atLeastOne){ 
    echo "Please check your hashtags!"; 
    exit; 
} 

注意我們在這裏檢查一個有效井號標籤,所以你需要從內刪除!您的if聲明。

+0

非常感謝!它已經工作了!注意:我可以在5分鐘內設置答案,我會這樣做! – ftxn 2014-10-18 18:30:56

+0

很高興有幫助。 – George 2014-10-18 18:31:13