Hey all,

I'm looking for a simple regex but I'm having trouble understanding how even the simple ones work, the site isn't really being of much use to me either!

So I was just wondering if someone could explain/show an example of how you can use eregi() to just determine whether a string contains ONLY letters (upper or lowercase) and numbers, but not any other characters.

I then want to expand this to allowing underscores and possibly dashes (-)however not as the first character or last character.. but that's not too important at the mo..

it seems logical, but I can't quite understand how you format it all..

Many thanks!

    STFI.
    http://www.regular-expressions.info/php.html

    RTFM.
    http://us3.php.net/eregi
    http://us3.php.net/manual/en/reference.pcre.pattern.syntax.php

    And as a general introduction, it's helpful to know that a regular expression is basically of the form
    #expression#pattern_modifiers

    where the # characters can be just that or other characters like / or maybe others. why are they there? I don't know...i think the basic idea is to delimit them from pattern_modifiers.

    patter_modifiers consists of single letter flags like i and s which tell the pattern matching subroutine, ereg, to ignore case (i) and match white space (s). more info on patter modifiers here:
    http://us3.php.net/manual/en/reference.pcre.pattern.modifiers.php

    here is an example php regular expression pattern creation:

    $pattern = "#[a-z]*#is"; // this pattern zero or more letters between a and z without regard to case
    

    The whole syntax of a pattern can be a tricky business and takes practice. This pattern will match a sequence of letters or digits and requires at least one letter or digit:

    $pattern = "#[a-z0-9]+#is";
    

    The ^ and $ characters match the beginning and end of your search string - UNLESS you also use a pattern modifier m which puts ereg in multiline mode. In that case they would refer to the beginning and end of a line. I don't know much about multiline mode. it's kind of confusing to me.

    so this partern might be useful, it should assert that your search string has at least one character and contains only letters and numbers:

    $pattern = "#^[a-z0-9]+$#is";
    

      Oh! I see, thanks very much for that! I've managed to get a kind of simple (but working!) regex now.. even though it seems to only work with preg_match not eregi..

      Cheers 😃

        Write a Reply...