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
)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值