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;
?>
// create a string$string = 'abcdefghijklmnopqrstuvwxyz0123456789';
echo preg_match("/abc/", $string);?>
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';
}?>
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