How to fix ‘Function eregi() is deprecated’ in PHP 5.3.0?

I used to use eregi for validating email address input that matches to the regular expression.

[raw]<pre>
if(!eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $str)) {
    $msg = 'email is not valid';
}
else {
$valid = true;
}</pre>
<p>[/raw]

That would return true if given email address is matches to username@domain.ext pattern. Unfortunately, after upgrading PHP to the earlier version (5.3.0), it wont work properly. This is because eregi is one of several functions that are deprecated in the new version of PHP.

Solution how to fix Function Deprecated:

Use preg_match with the ‘i’ modifier instead. i means that regular expression is case insensitive. So the code become like this:

[raw]<pre>
if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $str)) {
    $msg = 'email is not valid';
}
else {
$valid = true;
}</pre>
<p>[/raw]

The list of functions that are deprecated in PHP 5.3.0:

  • call_user_method() (use call_user_func() instead)
  • call_user_method_array() (use call_user_func_array() instead)
  • define_syslog_variables()
  • dl()
  • ereg() (use preg_match() instead)
  • ereg_replace() (use preg_replace() instead)
  • eregi() (use preg_match() with the ‘i’ modifier instead)
  • eregi_replace() (use preg_replace() with the ‘i’ modifier instead)
  • set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
  • session_register() (use the $_SESSION superglobal instead)
  • session_unregister() (use the $_SESSION superglobal instead)
  • session_is_registered() (use the $_SESSION superglobal instead)
  • set_socket_blocking() (use stream_set_blocking() instead)
  • split() (use preg_split() instead)
  • spliti() (use preg_split() with the ‘i’ modifier instead)
  • sql_regcase()
  • mysql_db_query() (use mysql_select_db() and mysql_query() instead)
  • mysql_escape_string() (use mysql_real_escape_string() instead)
  • Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
  • The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Ref:

http://php.net/manual/en/migration53.deprecated.php

$10.99 .CO Domains!

Incoming search terms:

  • Function eregi() is deprecated
  • Function ereg() is deprecated
  • Deprecated: Function eregi() is deprecated in
  • Deprecated: Function eregi() is deprecated
  • eregi
  • eregi deprecated
  • Function eregi() is deprecated in
  • Deprecated: Function ereg() is deprecated
  • Deprecated: Function ereg() is deprecated in
  • eregi is deprecated
  • vv

    Deprecated: Function ereg() is deprecated in C:\xampp\htdocs\catalog\admin\configuration.php on line 80

  • Keith

    Depreciated functions are really a pain, I hope there are no more of these in the next releases.

  • http://www.pixela.hu Miki (Pixela.hu)

    Sometimes it is better to use explode() instead of suggested split() —> preg_split()

    • takien

      yeah, sometimes explode is much easier and may be faster

  • dade

    so how do I fix this? I have searched and when I do apply the changed I still get an error. any assistance would greatly be appreciated.

    if ( eregi( ‘index.php\?’, $row->link ) ) {
    if ( !eregi( ‘Itemid=’, $row->link ) ) {
    $row->link .= ‘&Itemid=’. $row->id;
    }
    }

  • mike

    If you haven’t solved it yet…

    Sounds like a joomla template error change to:

    if ( explode( ‘index.php\?’, $row->link ) ) {

    if ( !explode( ‘Itemid=’, $row->link ) ) {
    $row->link .= ‘&Itemid=’. $row->id;
    }
    }

  • http://ajithex.tk ajith

    if(!preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i”, $str))

    this work fine in php 5.3..

    thankjs for solving

  • BandenX

    Ayo ramai2 gunakan PHP 5.2.x. Dah bosen gw pake PHP 5.3.x. Permasalahan deprecated function nggak ada solusi yg bener2 menyelesaikan masalah

    • takien

      wah, apa gak salah tuh keputusannya untuk mengingalkan PHP 5.3.x?
      Deprecated itu bukanlah masalah besar, hanya kode kita saja yang perlu di update (disesuaikan dengan perkembangan zaman), nanti di PHP 6, fungsi2 yang deprecated tersebut benar2 tidak ada lagi.
      ya, karena sudah ada fungsi lain yang sejenis yang bisa menggantikannya, biasanya lebih lengkap/mudah dsb.

    • websoldier

      Waduh kayaknya kamu masih pemula yah??

      Namanya pemula harusnya belajar, siap menghadapi tantangan versi baru. Karena versi lama bisa jadi boomerang tersendiri bagi kamu. Lah, yg satu ini malah aneh, ada-ada aja kamu malah pengen migrasi ke versi sebelumnya.

      Sebenernya kalo kamu mempelajari apa yang ada pasti masalah-masalah itu pasti bisa dibereskan,

      Salah satunya adalah masalah migrasi function deprecated ini, ini sebenarnya masih mudah loh masih bisa dengan mudah diselesaikan dibanding persoalan bug/vulnerability/error.

      Coba anda bayangkan persoalan error/bug/vulnerability codding itu, bukankah lebih rumit??

      So, belajar coding lah anda untuk mematangkan skill walaupun “Trial & Error”, jangan cuma “script kiddies” semata.

  • marek

    you can use ‘@’ (at sign) to suppress errors that would be generated from that expression.
    e.g:
    [php]
    if(!@preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i”, $str))
    [/php]
    then the errors won’t show up

    • http://www.dsparrowart.com amol sawant

      Nice Answer… it works for me……… tnks

  • http://www.link2vietnam.com Nguyễn Thế Bình

    Thank you so much! DONE! :D

  • Arief

    yes it works !!

    Please do what Mike suggest ..


    If you haven’t solved it yet…

    Sounds like a joomla template error change to:

    if ( explode( ‘index.php\?’, $row->link ) ) {

    if ( !explode( ‘Itemid=’, $row->link ) ) {
    $row->link .= ‘&Itemid=’. $row->id;
    }
    }

    it works for me !

    thanks Mike!

    regards,
    Arief

  • Pingback: Function eregi() is deprecated. | Coding Answers

  • http://www.oopsydaisy.ro/contact Puiu Darlea

    Can anyone helpt me with this?

    foreach($bad as $b) {
    if(eregi($b, $this->message)) {
    $this->naughty = true;
    }
    }

    If I replace “eregi” with “explode” I do not have the error anymore but I do not receive the mail either.

    If I replace “eregi” with “preg_match” I get this error
    “Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in /mnt/users/oopsydai/public_html/contact/process_form.php on line 109″
    BUT the mail is received.

    Any ideas would be highly apreciated!

    Puiu.

  • http://www.oopsydaisy.ro/contact Puiu Darlea

    I got it the right way, I am posting it in case others are in the same situation:

    if(eregi($b, $this->message))
    becomes:
    if(preg_match(“/\b”.$b.”\b/i”, $message))

    All the best to all!
    P.

    • takien

      Hello, Puiu Darlea. I was just about to reply to your comment but then you have found the solution. :D
      Furthermore, you need to use preg_quote in case your $b may contains special regex characters.

      good luck :)

      • Sdsd

        sdsds

        • Ss

          sdsdsd

          • Prasetya Rahastu

            sadgagf

          • Prasetya Rahastu

            afsafdad

  • http://www.oopsydaisy.ro/contact Puiu si Andreea

    Hi Takien, and THANK you for beeing present!

    Since I am no programmer, you mean simply change “preg_match” to “preg_quote” ?

    Some one helped me with this so I do not know the implications :)

    Thanks again for beeing present on this forum!
    Puiu

    • takien

      Sorry, I wasn’t so clearly explained you.
      No, not to change preg_match to preg_quote, they has different task.
      it should be like this:
      [php]
      if(preg_match(“/\b”.preg_quote($b).”\b/i”, $message))
      [/php]

      for more example and usability of preg_quote, just follow my link above.

  • Roberto79

    if(!ereg(“^[a-zA-Z0-9]*$”,$username))

  • Puiu Darlea

    ROBERTO79…

    I think it goes like this:

    if(preg_match(“/^[a-zA-Z0-9]*$/i”,$username))

    Let us know if it works!

    Ciao

    • Roberto79

      Works like a charm, thank you :)

    • http://www.yahoo.es kevin

      it’s work fine for me.!
      //if (eregi(‘(googlebot|slurp|crawler|spider|teoma|ask jeeves|robot|archiv|fireball|scooter|bot)’,$_agent)) {
      if(preg_match(‘(googlebot|slurp|crawler|spider|teoma|ask jeeves|robot|archiv|fireball|scooter|bot)’,$_agent)){

  • http://www.ericscalf.com Eric Scalf

    I’ve got the following code that is giving me fits in translating form eregi to preg_replace…
    if (eregi(“^” . rtrim(‘/’, $test) . “.*”, rtrim(‘/’, realpath($victim)))) {
    return true;
    }
    Just can’t get it down right… any ideas?

  • http://www.moonreturn.com/wp jay

    Thanks for very nice and easy solution

  • http://www.strongthink.net Faiz

    plz help me
    it is my code and i have problem in it
    if (eregi(“^(-)?[0-9]+\..$”, $totalbalance)) {
    $totalbalance .= “0″;
    }

    and this is error
    Deprecated: Function eregi() is deprecated in C:\wamp\www\echeckbook\echeckbook\checkbook.php on line 140

  • sachit

    Please solve this i can’t convert it

    if (eregi(‘^Version: [^0-9]*([ 0-9\\.\\:Q/]+)(http|file)\:’, $versionstring[1].’#i’, $matches)) {

  • Andre

    plz help me, ive tried every way, but i cant do it work ;x

    if(eregi(“[^0-9a-zA-Z_@:.?,]“, $post)){

  • Celeste

    Hi all,

    Plz help! I am stumped! Don’t understand what I’m doing wrong!!!

    I changed:
    /* Check is numeric*/
    $regex = “[0-9]{10}”;
    if(!ereg($regex,$field)){
    $form->setError($fieldValue, “* Contact number invalid”);
    }
    to:
    /* Check is numeric*/
    if(!preg_match(‘/[0-9]{10}/’,$field)){
    $form->setError($fieldValue, “* Contact number invalid”);
    }
    but still getting errors…..
    What am I doing wrong?

  • Pingback: PHP 5.3 Upgrade

  • pathros

    Thanks a lot! It worked!

  • patrick

    i have same problem Deprecated: Function ereg() is deprecated in and my php lines are

    if ( (eregi(‘create’, $next)) || (eregi(‘insert’, $next)) || (eregi(‘drop t’, $next)) ) {
    $next = ”;
    $sql_array[] = substr($restore_query, 0, $i);
    $restore_query = ltrim(substr($restore_query, $i+1));
    $sql_length = strlen($restore_query);
    $i = strpos($restore_query, ‘;’)-1;

    how should rewrite it?
    thanks

    • Anonymous

      try
      if ( (preg_match(‘/create/i’, $next)) || (preg_match(‘/insert/i’, $next)) || (preg_match(‘/drop/i’, $next)) ) {

  • http://savepdf.org Klary

    was very helpful … thank you

  • Pingback: Any Wordpress Experts here? - Page 2 - Graphic Design Forums: UK forums for graphic designers

  • Alex

    Cab¡n anyone hlep me with this one?

    function swap_formats($date, $startFormat, $endFormat) {
    $startreg = $this->get_regular_expression($startFormat);
    ereg($startreg['format'], $date, $regs);
    $newDate = $endFormat;

  • http://mehdibaaboura.wordpress.com Mehdi Baaboura

    thanks! that was very helpful!

  • http://www.register-web-domain.in Domain registration

    Great information Thanks to sharing it helping more 

  • Jeffshead

    How do I fix this:

    !eregi(basename($_SERVER['PHP_SELF']), $fileName) && ereg(‘^[^./][^/]*$’, $fileName))     

  • Suasssh

    Thank you this was a great help  

  • http://www.joomla-web-developer.com Joomla Development

    Several things in here’ haven’t considered before.Thank you for making this type of awesome publish that is really perfectly written, is going to be mentioning lots of buddies relating to this. Maintain blogging.

  • Dejavucomplete

    sathish

    Function ereg() is deprecated
     if(!ereg(“.*/index.php$”, $_SERVER['PHP_SELF'])
        && !ereg(“.*/axfr_get.php$”, $_SERVER['PHP_SELF'])) {
        header(“Location:../index.php”);
        exit;
    }

  • http://www.joomla-web-developer.com joomla developers

    Great work to fix this issue. Thanks for the code here. 

    • Anonymous

      you’re welcome :)

  • Vincent

    preg_match(‘/^(http|ftp)://’, substr($url, 0, 10))
    cant get this preg match working :( any1 that can help me with this one?

  • Nocniagenti

    Thnx for the info , is there any way to replace get_called_class()  to work with php 5.2 ?

    • Anonymous

      why don’t you upgrade PHP?

      Good news, I found this solution on php.net

      if(!function_exists(‘get_called_class’)) {

      function get_called_class() {

          $bt = debug_backtrace();

          $l = 0;

          do {

              $l++;

              $lines = file($bt[$l]['file']);

              $callerLine = $lines[$bt[$l]['line']-1];

              preg_match(‘/([a-zA-Z0-9_]+)::’.$bt[$l]['function'].’/',

                         $callerLine,

                         $matches);

                        

             if ($matches[1] == ‘self’) {

                     $line = $bt[$l]['line']-1;

                     while ($line > 0 && strpos($lines[$line], ‘class’) === false) {

                         $line–;                  

                     }

                     preg_match(‘/class[s]+(.+?)[s]+/si’, $lines[$line], $matches);

             }

          }

          while ($matches[1] == ‘parent’  && $matches[1]);

          return $matches[1];
        }
      }

  • http://www.r-gate.net/ Mohamed Tair

    Thanks a lot !!
    ^^

  • http://www.facebook.com/dortland Laurens Dortland

    Hi all,

    How do I need to rewrite the following line?

    $stylesheet = ereg_replace(“{/?php}”, “”, $stylesheet);

    Thanks!
    Laurens

    • Anonymous

      try this
      $stylesheet = preg_replace(“/{/?php}/”, “”, $stylesheet);

  • Boes4n

    i have same problem Deprecated: Function ereg() is deprecated in and my php lines are

    how should rewrite it?
    thanks

    • Anonymous

      try this:

      $dom = ”;                                
      if(!preg_match(“/authentication/i”,$_SERVER['PHP_SELF']) || preg_match(“/catalog/i”,$_SERVER['PHP_SELF']))
          $dom = ‘../’;    
      if(!preg_match(“/control/i”,$_SERVER['PHP_SELF']))
          $dom = ‘control/’;    
      include($dom.”connect/config.php”);
      include($dom.”connect/myconnect.php”);

  • Aiden

    first and foremost I want to thank who created this link, this is very helpful and how can I fix this error I encountered it says “Deprecared: Function eregi_replace()”

    here’s the code

    foreach($badword_array as $insult=>$ok){
            $cjmsg = eregi_replace(“$insult”, “$ok”, “$cjmsg”);
            }

    foreach($badword_array as $insult=>$ok){
            $name = eregi_replace(“$insult”, “$ok”, “$name”);
            }

    thanks in advance and more power.