Voting

: nine minus nine?
(Example: nine)

The Note You're Voting On

Stefan
15 years ago
I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0.

Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters.

The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty.

ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value.

Here is an example code snippet to illustrate:

<?php
$test
= array('yes','no','yes','no','yes','no');

foreach (
$test as $key=>$value) {
ereg("yes",$value,$matches1);
preg_match("|yes|",$value,$matches2);
}
print
"ereg result: $matches1[0]<br>";
print
"preg_match result: $matches2[0]<br>";
?>

The output is:
ereg result: yes
preg_match result:

($matches2[0] in this case is empty)

I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time.

<< Back to user notes page

To Top