• php中ereg() ,preg_match() 与preg_match_all的区别?代码详细比较


    PHP中几个正则函数的用法及区别
    函数用法:
    preg_match(mode, string subject, array matches); 相比ereg更加规范,执行效率越高
    ereg(mode, string subject, array regs);
    mode:正则表达式(preg_match中的mode必须以’/'开始和“/”结束)
    subject: 需要验证的字符串
    matchs/regs: 匹配后得到的结果。以数组的形式存储
    preg_match和 preg_match_all区别是preg_match只匹配一次。而preg_match_all全部匹配,直到字符串结束。

    示例如下:
    <?php
    $date = date(‘Y-m-d’);
    //ereg函数
    ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})",$date,$rs);
    var_dump($rs);
    unset($rs);
    echo "—————————————–<br>";
    //preg_match函数
    preg_match("/([d]{4})-([d]{1,2})-([d]{1,2})/",$date.$date,$rs);
    var_dump($rs);
    unset($rs);
    echo "—————————————–<br>";
    //preg_match_all函数
    preg_match_all("/([d]{4})-([d]{1,2})-([d]{1,2})/",$date.$date,$rs);
    var_dump($rs);
    ?>
    如下输出:
    array(4) {
    [0]=>
    string(10) "2012-08-20"
    [1]=>
    string(4) "2012"
    [2]=>
    string(2) "08"
    [3]=>
    string(2) "20"
    }
    —————————————–
    array(4) {
    [0]=>
    string(10) "2012-08-20"
    [1]=>
    string(4) "2012"
    [2]=>
    string(2) "08"
    [3]=>
    string(2) "20"
    }
    —————————————–
    array(4) {
    [0]=>
    array(2) {
    [0]=>
    string(10) "2012-08-20"
    [1]=>
    string(10) "2012-08-20"
    }
    [1]=>
    array(2) {
    [0]=>
    string(4) "2012"
    [1]=>
    string(4) "2012"
    }
    [2]=>
    array(2) {
    [0]=>
    string(2) "08"
    [1]=>
    string(2) "08"
    }
    [3]=>
    array(2) {
    [0]=>
    string(2) "20"
    [1]=>
    string(2) "20"
    }
    }
    PHP中如何用正则函数来验证中文字符串
    验证中文字符串正则表达式为: /^[x{4e00}-x{9fa5}]+$/u
    方法如下:
    $str = "个人博客";
    if(preg_match("/^[x{4e00}-x{9fa5}]+$/u",$str)){
    echo ‘皆为中文’;
    }else{
    echo ‘不完全是中文’;
    }
  • 相关阅读:
    抽奖代码
    org.hibernate.AssertionFailure: null id in com.you.model.User entry (don't flush the Session after a
    Cannot add or update a child row: a foreign key constraint fails
    SyntaxError:identifier starts immediately after numeric literal
    too much recursion
    微信处理红包
    minerd
    minerd
    kill常用
    阿里云centos 6安装Nginx+PHP+MySQL
  • 原文地址:https://www.cnblogs.com/paddygege/p/6957303.html
Copyright © 2020-2023  润新知