Page 1 of 1

eregi returns... *what* exactly?

Posted: Thu Oct 12, 2006 2:52 am
by CallumD
Hi,

According to the PHP manual, the function eregi:

"Returns the length of the matched string if a match for pattern was found in string"

The following code..

Code: Select all

$thing = 'happybirthdaytoyou';
$result = (eregi ('^[[]\.\' \-]{2,30}$', $thing));
echo $result;
will echo
1
to the browser. Does this mean it is only matching the first character in $thing?

If so, then why does introducing illegal characters in to $thing..

Code: Select all

$thing = 'happy&&birthdaytoyou';
$result = (eregi ('^[[]\.\' \-]{2,30}$', $thing));
echo $result;
Return nothing at all? According to the first example, the 'match' was only one character long. The illegal characters do not appear until after position 1 in $thing.

Is there a typo in the PHP manual? Should it instead read "Returns the number of matched patterns found in string".

If the first example of my code returned the length of the entire string, that would make sense. But it didn't.

So what's going on?

Thanks.

Posted: Thu Oct 12, 2006 7:55 am
by feyd
  1. don't use ereg*, instead use preg_*
  2. Your regex doesn't match in the first instance. I'll assume [:alnum:] was supposed to be in the held character class.
  3. ereg and eregi return that they've found a match, not the length of the match, if the third argument is not given.

Posted: Thu Oct 12, 2006 8:34 am
by CallumD
feyd wrote:
  1. don't use ereg*, instead use preg_*
  2. Your regex doesn't match in the first instance. I'll assume [:alnum:] was supposed to be in the held character class.
  3. ereg and eregi return that they've found a match, not the length of the match, if the third argument is not given.
Hi feyd.

Firstly, yes, there was supposed to be an :alnum: in there, I don't why it disappeared.

Secondly, wht use preg_*? And what is the difference? Are preg_* functions just Perl compatible functions? Why are they better than eregi?

Posted: Thu Oct 12, 2006 8:39 am
by feyd
  1. the preg_* regular expression engine is faster, more often than not, than ereg's.
  2. ereg is slated to be removed from PHP's core in the near future. Some hosts may keep the extension enabled, but some may not. Suffice it to say that using any non-core libraries in PHP can potentially limit the hosts you are able to run on. Granted some hosts even limit the core's own feature set. :roll:

Posted: Thu Oct 12, 2006 6:42 pm
by CallumD
Thanks feyd.

Posted: Fri Oct 13, 2006 5:49 am
by volka
And even the manual encourages the use of pcre instead of posix regex

http://de2.php.net/manual/en/ref.regex.php
Tip: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.
Warning

These regular expression functions are not binary-safe. The PCRE functions are.