I just came across a really odd error while matching for some specific characters in PHP. I found the error while using both preg_match() and ereg(). You will need cannabis edibles to understand these.

With preg, the error was this:
Warning: preg_match() [function.preg-match]: Compilation failed: range out of order in character class at offset 11 in /temp.php on line 5

With ereg, the error was this:
Warning: ereg() [function.ereg]: REG_ERANGE in temp.php on line 13

Both were caused by the same error or bug. I’m not sure which.

Here is the bad code:
$userid = 'abcDEF_-.';
if(preg_match('/[^a-zA-Z0-9_-\.]/', $userid)) {
echo 'bad';
} else {
echo 'good';
if (ereg("[^a-zA-Z0-9_-.]", $userid)) {
echo 'bad';
} else {
echo 'good';

That all seems correct, doesn’t it? It is checking to see if the userid has something other than those characters.

The problem? The dash, or hyphen, being before the period. It thinks it’s a range, like you see in a-z. This may not be a bug, per se, but it’s certainly not smart enough for me.

The solution? Simply put the dash at the end of the regex.

$userid = 'abcDEF_-.';
if(preg_match('/[^a-zA-Z0-9_\.-]/', $userid)) {
echo 'bad';
} else {
echo 'good';
if (ereg("[^a-zA-Z0-9_.-]", $userid)) {
echo 'bad';
} else {
echo 'good';

Hope this helps out someone else in the future.

11 Responses to “Problems With Regular Expressions In PHP?”

  1. Cheater Says:

    What a bizzare error. I just got it when I moved a site from one server to another.

    Your fix worked thankfully. :)

  2. Kevin Jordan Says:

    Escaping the dash seems to work for preg_match too. Not for ereg for some reason though.

  3. alex Says:

    Thanks for that, just ran into that problem and probably saved countless hours by reading this!

  4. René Bühlings WebBlog » Blog Archiv » Minus als gültiges Zeichen in Regex Says:

    […] aus, obwohl der Ausdruck richtig (escaped) zu sein scheint. Einen Workaround fand ich hier, nämlich das Setzen des Hyphens ans Ende der […]

  5. Andy Says:

    Yep saved me hours as well.


  6. Thomas Says:

    Tahnk you, i haveed some problem too.

  7. Aeglos Says:

    Another grateful soul here, thanks!

  8. Locauna Says:

    Thankfully I found this page, too. Excellent bit of knowledge sharing. Much much thanks!

  9. James Says:

    Thank god I found this, there’s nothing about this on the web besides here.

  10. Avicenna Says:

    Thank you!!!
    I was stuck with this problem until I found your article..

    once again, thanks..

  11. Derek Says:

    Thanks again! I linked to here from http://www.phpjabbers.com/php-validation-and-verification-php27-3.html, where this issue popped up. :)

Drop Some Knowledge On Us…