Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Start of String and End of String Anchors For Single Character Clause

Tags:

regex

php

Sorry for the NOOB factor but what are these two regi (regex plural lol) doing differently?

http://codepad.viper-7.com/vaQTMh

    <?php

    $name = 'BartSimpson';
    $regex1 = '#^[A-Z]$#i';
    $regex2 = '#[A-Z]#i';


    if (preg_match($regex1, $name)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }


    if (preg_match($regex2, $name)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }

    ?>
like image 561
user784637 Avatar asked Oct 10 '22 12:10

user784637


1 Answers

The first one has, as you have noted, start/end of string anchors. So it will only match if the string you give it contains exactly one character in the range [A-Z].

The second, having no anchors, matches a string that contains at least one character in the range [A-Z], anywhere in its contents.

Please spend some time reading about regular expressions (for example here http://www.regular-expressions.info/). This is very basic.

like image 83
Mat Avatar answered Oct 20 '22 07:10

Mat