PHP中ereg与preg_match和preg_match_all函数的区别

作者: unvs 分类: PHP 发布时间: 2012-08-20 10:11 ė110,296 views 6没有评论

今天查找资料了解了下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 ‘不完全是中文’;
}
刚发现之前发表过一篇JS判断汉字的正则表达式文章,附上地址:http://blog.unvs.cn/archives/chinese-regular-expression.html

本博文章基本上属于原创或收集整理,都是心血结晶。
欢迎转载分享,转载请注明出处,谢谢!
本文地址:PHP中ereg与preg_match和preg_match_all函数的区别

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Ɣ回顶部