1

I'm going through my code to replace any instances I'm using the ereg() function - which I was using for matching regex inside a string.

I could use a little direction, if someone has a better method than what I'm using.

Here's my old "currency validation" script:

    function valid_currency($number){
     if(ereg('^[0-9]+\.[0-9]{2}$', $number))
      return true;
     else
     return false;
    }

    if(valid_currency(25.30)){ 
          echo "valid currency"; 
   }else{ 
          echo "invalid currency string"; 
   }

I replaced the ereg() with preg_match().

I'm getting this error now:

Warning: preg_match() [function.preg-match]: No ending delimiter '^'

I'm guessing the regular expression syntax isn't being recognized. From here I'm a little stuck.

Daniel Egeberg
  • 8,359
  • 31
  • 44
coffeemonitor
  • 12,780
  • 34
  • 99
  • 149

3 Answers3

5

preg requires delimiters around your regex. It can be almost anything though traditionally it's /. This should work:

preg_match('/^[0-9]+\.[0-9]{2}$/', $number)
Cfreak
  • 19,191
  • 6
  • 49
  • 60
0

You need the bounds for the regex statement, IE it's thinking you're starting the statement with ^ and saying there's no ending ^ indicating the end of the statement. Use /^[0-9]+\.[0-9]{2}$/ instead

Robert
  • 21,110
  • 9
  • 55
  • 65
  • You're right! I was ALMOST doing it correct. I wasn't paying attention to the ending delimiter. I knew it was something mundane. thanks for making that more obvious. – coffeemonitor Aug 15 '10 at 21:00
0

in preg_match() or preg_match_all() uses "delimiters".examples:

/regEx/ or #regEx# or |regEx| or @regEx@.

I use: /regEx/

function valid_currency($n) { 
                    return preg_match("/^\d+\.\d{2}$/", $n);
        }

returns bool: 1(true) 0(false)

exmaple of use:

echo valid_currency("25.30") ? 'valid currency' : 'invalid currency string';
Jet
  • 1,283
  • 10
  • 7