开发者

Switching from PHP !ereg and !eregi to preg_match [duplicate]

This question already has answers here: How can I convert ereg expressions to preg in PHP? (4 answers) Closed 8 years ago.

I hope someone can help!!!

In coding a form validation, I got the error message开发者_StackOverflow "Deprecated: Function ereg() is deprecated in E:\Zacel_Development\sa_model_watch.co.za\insert_newProf.php on line 184"

I did some research and found out I need to change !eregi and !ereg to preg_match...

I did try this, but to no avail... can anyone please check my code and advise as I am stumped!

My Code Snippet:

/* Check is numeric*/
$regex = "[0-9]{10}";
   if(!ereg($regex,$field)){
   $form->setError($fieldValue, "* Contact number invalid");
   }

SHOULD APPARENTLY BE:

/* Check is numeric*/
$regex = "[0-9]{10}";
 if(!preg_match($regex,$field)){
 $form->setError($fieldValue, "* Contact number invalid");
 }

AND:

/* Check if valid email address */
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
     ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
     ."\.([a-z]{2,}){1}$";
    if(!eregi($regex,$field)){
      $form->setError($fieldValue, "* Email invalid");
      }

SHOULD APPARENTLY BE:

/* Check if valid email address */
$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
     ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
     ."\.([a-z]{2,}){1}$";
    if(!preg_match($regex,$field)){
      $form->setError($fieldValue, "* Email invalid");
      }

This still doesn't work... What am I doing wrong?


You have to open and close your regex pattern with a delimiter:

So that:

$regex = "[0-9]{10}";

becomes

$regex = "/[0-9]{10}/";

If you want the pattern to be case insensitive use the i flag

$regex = "/somepattern/i";


here you are some example:

over from ereg, preg_match can be quite intimidating. to get started here is a migration tip.

<?php
if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z.

if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required.
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜