Wednesday, March 2, 2011

check if string is regex php ?

What is a regex?


At its most basic level, a regex can be considered a method of pattern matching or matching patterns within a string. In PHP the most oft used is PCRE or "Perl Compatible Regular Expressions". Here we will try to decypher the meaningless hieroglyphics and set you on your way to a powerful tool for use in your applications. Do not try to understand all this in a single sitting. Instead, take in a little and come back as you grasp various concepts.

Where do I begin?

At the beginning.
Lets create a string.

// create a string$string 'abcdefghijklmnopqrstuvwxyz0123456789';
// echo our stringecho $string;
?>
If we simply wanted to see if the pattern 'abc' was within our larger string we could easily do something like this:
// create a string$string 'abcdefghijklmnopqrstuvwxyz0123456789';

echo 
preg_match("/abc/"$string);?>
The code above will echo '1'. This is because it has found 1 match for the regex. That means it has found the pattern 'abc' once in the larger string. preg_match() will count zero if there is no matches, or one if it finds a match. This function will stop searching after the first match. Of course, you would not do this in a real world situation as php has functions for this such as strpos() and strstr() which will do this much faster.

Match beginning of a string

Now we wish to see if the string begins with abc. The regex character for beginning is the caret ^. To see if our string begins with abc, we use it like this:
// create a string$string 'abcdefghijklmnopqrstuvwxyz0123456789';
// try to match the beginning of the stringif(preg_match("/^abc/"$string))
    {
    
// if it matches we echo this line
    
echo 'The string begins with abc';
    }
else
    {
    
// if no match is found echo this line
    
echo 'No match found';
    }
?>
From the code above we see that it echo's the line
The string begins with abc
The forward slashes are a delimeter that hold our regex pattern. The quotations are used to 'wrap it all up'. So we see that using the caret(^) will give us the beginning of the string, but NOT whatever is after it.

No comments:

Post a Comment