Regular Expressions
2003-02-17 00:24:06
Category: php:general
Description: Example on using ereg, eregi, ereg_replace, and eregi_replace.
Author: detour
Viewed: 3693
Rating: (8 votes)


<?php
  // ereg.php by detour@metalshell.com
  //
  // Example on using ereg, eregi, ereg_replace, and
  // eregi_replace().
  //
  // http://www.metalshell.com/
  //
 
 
  $str1 = "cat dog mouse";
  $ipnum = array("127.0.0.1",
                 "255.255.255.255",
                 "204.28.82.290",
                 "209.192.28.28.34");
 
  // ereg() is case sensitive so CAT will not be found
  if( ereg("CAT", $str1) )
    echo('CAT found.<br>');
  else
    echo('CAT not found.<br>');
 
  // eregi() is case insensitive so dog is found
  if( eregi("dog", $str1) )
    echo('dog found.<br>');
  else
    echo('dog not found.<br>');
 
  // Replace 'mouse' with 'cat'
  if( $str1 = ereg_replace("mouse", "CAT", $str1) )
    echo('mouse replaced with cat<br>');
  else
    echo('mouse not found.<br>');
 
  echo('$str1 now equals "' . $str1 . '"<br>'); 
 
  // Case insensitive replace
  if( $str1 = eregi_replace("cat", "mouse", $str1) )
    echo('cat and CAT replace with mouse<br>');
  else
    echo('no match for cat<br>');
 
  echo('$str1 now equals "' . $str1 . '"<br>'); 
 
  // Cycle through the ip array and test each one
  foreach ($ipnum as $ipn) {
    if(valid_ip($ipn))
      echo("$ipn is a valid ip.<br>");
    else
      echo("$ipn is an invalid ip.<br>");
  }
 
  // Takes an ip as an arg and tests to see if it is valid
  function valid_ip($ip) {
    if( ereg( "^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$", $ip, $res ) ) {
      for($x = 1; $x < 5; $x++)
        if($res[$x] > 255)
          return FALSE;
    } else {
      return FALSE;
    }
 
    return TRUE;
  }
 
?>