• 0

[PHP] eregi replacement


Question

I've been using this code to validate user names. It only allows 0-9, a-z, A-Z, spaces...

if ( ! eregi ( "^[0-9A-Z_[:space:]]{1,}$", $username ) )

But now, in PHP 5.3 the ereg and eregi functions are deprecated and will be deleted in PHP 6.0.

How can I do this without eregi?

Edited by MNunes2
Link to comment
https://www.neowin.net/forum/topic/815802-php-eregi-replacement/
Share on other sites

15 answers to this question

Recommended Posts

  • 0

you're close. preg_* functions use perl regular expressions so they have a little extra syntax to them.

preg_match("/^[0-9a-z_ ]+$/i", &username)

mainly the starting and ending slash. the letter 'i' after the ending slash says "do a case insensitive search". that way you can remove the extra A-Z character class.

  • 0
you're close. preg_* functions use perl regular expressions so they have a little extra syntax to them.
preg_match("/^[0-9a-z_ ]+$/i", &username)

mainly the starting and ending slash. the letter 'i' after the ending slash says "do a case insensitive search". that way you can remove the extra A-Z character class.

And what does this +$ and this ^ mean? And where can I learn more about this?

  • 0

a carrot (^) means to assert position at the beginning of the string. so basically.. this pattern needs to start at the very beginning of the string.

the dollar sign ($) means assert position at the end of the string. so the strings needs to end with this pattern as well.

the stuff between the square braces are known as a character class. a group of characters that must exist (in this case). if you left the plus off after the character class then that character class would only be required to match one character. the plus means match at least one of the characters in the character class.. but the more it finds in next to each other the more it will match.

so when you put it all together it says that some string must start with and end with some number, letter, space, or any of the symbols (&, #, _) and it must exist at least once but can exist as many times as possible.

if you leave the carrot or dollar sign off of the expression then a pattern could be satisfied anywhere in the string and would be considered a match. for example.. if you used the pattern "[0-9a-z_ ]+" and tested it against the string "abc;.123" it would match two patterns: "abc" and "123". using the dollar sign and carrot it would start matching and get to "abc" then it would see a semicolon and because a semicolon isnt in the character class the pattern fails because the entire string wasnt the match for the pattern.

the key thing to remember is that a regular expression will look for any match that it can find if you dont use constraints like these.

  • 0
a carrot (^) means to assert position at the beginning of the string. so basically.. this pattern needs to start at the very beginning of the string.

the dollar sign ($) means assert position at the end of the string. so the strings needs to end with this pattern as well.

the stuff between the square braces are known as a character class. a group of characters that must exist (in this case). if you left the plus off after the character class then that character class would only be required to match one character. the plus means match at least one of the characters in the character class.. but the more it finds in next to each other the more it will match.

so when you put it all together it says that some string must start with and end with some number, letter, space, or any of the symbols (&, #, _) and it must exist at least once but can exist as many times as possible.

if you leave the carrot or dollar sign off of the expression then a pattern could be satisfied anywhere in the string and would be considered a match. for example.. if you used the pattern "[0-9a-z_ ]+" and tested it against the string "abc;.123" it would match two patterns: "abc" and "123". using the dollar sign and carrot it would start matching and get to "abc" then it would see a semicolon and because a semicolon isnt in the character class the pattern fails because the entire string wasnt the match for the pattern.

the key thing to remember is that a regular expression will look for any match that it can find if you dont use constraints like these.

It's caret. lol

  • 0
It's caret. lol

:rofl: lol my fingers must be hungry

It seems I will have to learn a lot about this function since ereg functions wont be available anymore. :-( Thanks for the information.

i learned mostly from using regex buddy and reading their docs on their site. i think it's a great app for easing into regular expressions and testing/debugged really complex ones even after you get the hang of it.

http://www.regexbuddy.com/regex.html

  • 0

Hi guys,

been a few years since i've used PHP and was testing out some old stuff I had, and came across the depreciated ereg function.

I was using:

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

which I picked up form somewhere, have no idea how it works, and so have no idea how to turn it into preg_match.

Anyone lend a hand? I tried some solutions already in the thread but didn't have much luck.

My function looks like:

function valid_email($address)

{

// check an email address is possibly valid

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

return true;

else

return false;

}

  • 0

I've been using this code to validate user names. It only allows 0-9, a-z, A-Z, spaces...

if ( ! eregi ( "^[0-9A-Z_[:space:]]{1,}$", $username ) )

But now, in PHP 5.3 the ereg and eregi functions are deprecated and will be deleted in PHP 6.0.

How can I do this without eregi?

I've been using the following code to validate Xbox Live Gamertags in a Stats application. (which is A-Z, a-z, 0-9, spaces)

preg_replace('/[^a-zA-Z0-9\s]/', '', $username);

or if you have more descriptive stuff (like can't start/end with space, can't have 2 spaces in a row, can't start in a number, 15 chars long)

preg_replace('/^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/', '', $username);

  • 0

Hi guys,

been a few years since i've used PHP and was testing out some old stuff I had, and came across the depreciated ereg function.

I was using:

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

which I picked up form somewhere, have no idea how it works, and so have no idea how to turn it into preg_match.

Anyone lend a hand? I tried some solutions already in the thread but didn't have much luck.

My function looks like:

function valid_email($address)

{

// check an email address is possibly valid

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

return true;

else

return false;

}

Seeing as you're using newer PHP, I'd suggest filter_var

  • 0

If you want to learn about regular expressions then I would suggest reading up on the Perl Regex man page.

A more user friendly website for learning about regex is http://www.regular-expressions.info/, but this teaches PCRE (Perl Compatible Regular Expressions). As the name suggests the two are mostly the same, but there are some minor inconsistencies.

  • 0

I've been using the following code to validate Xbox Live Gamertags in a Stats application. (which is A-Z, a-z, 0-9, spaces)

preg_replace('/[^a-zA-Z0-9\s]/', '', $username);

\s matches all whitespace, not just spaces. It will also match tabs, line feeds, carriage returns, which are clearly not allowed in XBL gamertags :p

If you want to match only spaces then you should use [^a-zA-Z0-9 ].

Also, rather than match a-zA-Z you could use the /i case-insensitive modifier. With the above changes, the final regex would become:

preg_replace('/[^a-z0-9 ]/i','',$username);

Or if you prefer, you can use \d instead of 0-9:

preg_replace('/[^a-z\d ]/i','',$username);

  • 0

Hi guys,

been a few years since i've used PHP and was testing out some old stuff I had, and came across the depreciated ereg function.

I was using:

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

which I picked up form somewhere, have no idea how it works, and so have no idea how to turn it into preg_match.

Anyone lend a hand? I tried some solutions already in the thread but didn't have much luck.

My function looks like:

function valid_email($address)

{

// check an email address is possibly valid

if (ereg('^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$', $address))

return true;

else

return false;

}

function valid_email($address)
{
  // check an email address is possibly valid
  return (preg_match('/^[a-z\d_\.\-]+@([a-z\d\-]+)(?:\.(?1))+$/i',$address)) ? true : false;
}

Your original regex matched things like "[email protected]" which is clearly not a valid email address. This one will not match that.

I'm not a PHP programmer so the above may not work if I've got any of the PHP syntax wrong, but I've tried out the regex in another language and it seems to work :)

Edit:

In fact, if top level domains only ever go two levels deep, like ".co.uk," then this regex is probably more appropriate:

function valid_email($address)
{
  // check an email address is possibly valid
  return (preg_match('/^[a-z\d_\.\-]+@([a-z\d\-]+)(?:\.(?1)){1,2}$/i',$address)) ? true : false;
}

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Meta will now use data from outside businesses to personalize AI responses by David Uzondu In an update that's rolling out globally (except in a handful of countries), Meta will use your data from outside businesses to personalize your AI responses and your primary feeds. Meta already utilizes your shopping activity to target ads, but the company now plans to expand this tracking to personalize other "parts of your experience" like feed algorithms and AI assistant chats. The company is replacing the two settings ("Your activity off Meta technologies" and "Activity from other businesses") that currently let you disconnect off-platform activity with a single, renamed setting called Activity from other businesses. If you don't want Meta to manipulate your feed and AI responses using your outside history, you can just turn the Activity from other businesses setting off in your account settings. This toggle resides within your Accounts Center, applying your choice to every connected profile. Turning this off will not stop companies from sending your data to Meta. The company will still collect your web interactions, but it only uses them to train products, while still accessing external accounts you connect. When The Verge spoke to Meta spokesperson, Emil Vazquez, the representative said that this update will exclude several locations at launch including the European region, the UK, Brazil, Thailand, South Africa, Turkey, South Korea, Ecuador, Nigeria, and Kenya. The new update comes at a time when the social media giant is recovering from a major PR disaster involving generative AI. Last week, there was a huge security issue on Instagram where attackers figured out a way to exploit a prompt injection vulnerability. Hackers managed to trick Meta AI into handing over account ownership (even if the victim had 2FA enabled). Some of the affected accounts include the dormant Obama White House profile, cosmetics brand Sephora, the Chief Master Sergeant of the Space Force, and security researcher Jane Manchun Wong. Internally, the company also had to scale back plans on its Model Capability Initiative (MCI), an employee-monitoring program designed to train corporate AI models by recording worker keystrokes and screen activity, after employees raised privacy concerns and complained about severe battery life drain.
    • JetBrains is working to cut false positives in RustRover 2026.2 by David Uzondu Recently, JetBrains released the fifth EAP build of its dedicated IDE, RustRover 2026.2, bringing improvements like a Run gutter icon for criterion_main! macro benchmarking and a feature that alerts you when there are unused traits in your current scope. Now, the company is out with a blog post addressing one of the "most common" complaints from users: false positives. In RustRover, a false positive occurs when the editor incorrectly highlights something as an error even though the project compiles and runs successfully. This mismatch flags a gap between the IDE's internal intelligence and the actual compiler. When the editor flashes red warnings over perfectly valid code, developers lose trust in the tool, which stalls momentum. Traditionally, RustRover runs cargo check to detect compiler errors and warnings, but it also relies on its own code analysis engine to power real-time features. To provide quick feedback, this engine parses your source code into a syntax tree while inferring types and resolving names as you type. Because this engine must work on broken, half-written code and react instantly, its logic sometimes diverges from the compiler's, producing false positives that do not exist in the compiler's eyes. JetBrains said that it has a "dedicated task force" focused specifically on identifying and fixing false positives by analyzing user reports and examining large-scale open-source projects. To speed up this process, the team built an internal system modeled after Crater, the famous Rust project that compiles and runs tests for every single crate published on crates.io. This automated pipeline compares the diagnostics from RustRover's analysis with actual compiler output to catch discrepancies before they reach users, ensuring smoother workflows. RustRover, for those who're unaware, is a dedicated IDE designed specifically for Rust developers. It's been around for a couple of years now, providing features like built-in debugging via LLDB, seamless cargo integration, advanced macro expansion, and HTML support. JetBrains distributes the app under two licensing models: a paid commercial subscription and a free option for non-commercial use.
    • Last year I bought the 2TB variant for $114 on Amazon. That's crazy that the 1TB is now 67% more expensive for half the storage, even with the newer T9 already on the market. And that's considered a good deal.
    • You can disable all non needed features from Brave. There is also Brave Origin which removes them entirely and it is free for Linux.
    • I wish I could use Brave but the tab suspension feature is horrible. It doesn't suspend them like Edge does. Even after 2h open with 70+ tabs (same as Edge), it has 2GB more consumption than Edge for no reason.
  • Recent Achievements

    • One Year In
      Primer1st earned a badge
      One Year In
    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      512
    2. 2
      PsYcHoKiLLa
      229
    3. 3
      Edouard
      135
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      81
  • Tell a friend

    Love Neowin? Tell a friend!