r/PHPhelp • u/nuno14 • Sep 08 '25
Solved Question Function ereg() is deprecated
Hello
Noob here, learning as I go along. I inherited a site with an old script and I'm getting some errors I'd like to correct, this one is the most common.
I googled and I'd just like to know if I'm thinking this right.
If I have this:
if (ereg('[^0-9]',$id)) {
header("Location: index.php"); break;
}
if (ereg('[^0-9]',$p)) {
header("Location: index.php"); break;
}
I need to change it to this?
if (preg_match(/[^0-9]/,$id)) {
header("Location: index.php"); break;
}
if (preg_match(/[^0-9]/,$p)) {
header("Location: index.php"); break;
}
Is this correct?
Thanks
Edit: thank you all for the help, i got it now :)
4
u/allen_jb Sep 08 '25
For reference you can find documentation for the ereg functions in the legacy documentation maintained by Zend: https://php-legacy-docs.zend.com/manual/php5/en/function.ereg
At a glance that looks right, other than the missing quotes around the regular expression.
You can test the code yourself using an online sandbox, or the
php -ainteractive commandline (there are also more featureful REPL libraries available).See https://3v4l.org/GBDpp
If you want to match the whole string, use
'/^[0-9]+$/'Side note: You may be tempted to use the mb_ereg functions which currently still exist in PHP, however it looks like it's quite likely these are about to be deprecated because the underlying library is no longer maintained. See https://wiki.php.net/rfc/eol-oniguruma (discussion: https://externals.io/message/128522 and https://externals.io/message/127245 )
3
u/eurosat7 Sep 08 '25
Lookup rector/rector to autofix stuff.
2
u/FreeLogicGate Sep 08 '25
Someone else already point out, that, unlike javascript (not sure if that is where you are coming from) the regex parameter is a string, so no, your code would cause a runtime error. With quotes around the regex, it will. The perl regex's require a delimiter around the regex, which you have. One thing that allows you to do is have modifiers in the regex expression, like
'/HI/i'This site is great for testing: https://regex101.com/
So, yeah, this is equivalent: