PHP自學筆記14--判斷輸入中符合條件的字符數

PHP持續學習中。

判斷字符數其實很簡單,用strlen()就可以了。

這裏要說的是使用正則表達式,符合條件的字符數。換行啦(換行算兩個字符),空白符啦,全都給你算上。

 

代碼如下:

1,文件1,用於輸入

<?php 
$html=<<<start1
<html>
<head>
<script type="text/javascript">
function check(){
    if(document.myform.text1.value==""){
        alert("please input content");
        return false;
    }
    document.myform.submit();
}
</script>
</head>
<body>
<form name="myform" action="test014_check.php" method="post">
  content:<input type="text" name="text1" value=""/>
  <br/>
  <input type="button" onclick="check()" value="check content"/>
</form>
</body>
</html>
start1;

echo $html;

?>

2,文件2,名爲test014_check.php,用於判斷文件1的輸入是否大於10個字符

<?php 
echo "<pre>";
if(!empty($_POST['text1'])){    
    $str=$_POST['text1'];
    $match="";
    preg_match_all("/./us", $str,$match);
    print_r($match);
    print_r($match[0]);
    
    $num=count($match[0]);
    
    //echo "<br/>".$num;
    
    if($num<=10){
        echo "<script>alert('inputted is litte than 10');</script>";
    }else{
        echo "<script>alert('publish success');</script>";        
    }
}
echo "</pre>";
?>

這裏比較有意思的是preg_match_all函數,匹配出來的東西放到$match二維數組裏。

當然啦,這大炮打蚊子,preg_match_all可不是用來算字符長度的,而是用來匹配的,

所以這個例子是算匹配後的字符數。

 

比如文件1中輸入 0123456789a,則輸入如下。

只要判斷match[0] 數組的長度即可。

但本文想說的是正則表達式 /./us,這是什麼意思呢。

修飾    說明
i    忽略大小寫
s    忽略換行,當成一行來看待
u    使用UTF-8字符集來處理
e    替換之後,當作php代碼來執行

 

<參考:日文的,想看的朋友湊活看吧>

https://qiita.com/tsuuuuu_san/items/b88b0662426f2b956c77

 

<參考2:另一篇匹配字符串的文章>

https://www.cnblogs.com/52php/p/5677640.html

 

輸出:

<這裏是$match>

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
            [5] => 5
            [6] => 6
            [7] => 7
            [8] => 8
            [9] => 7
            [10] => 9
            [11] => a
        )

)

<這裏是match[0]>

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 7
    [10] => 9
    [11] => a
)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章