This kind of pattern matching is what "regular expressions" are all about. They do all you want and a whole bunch more.
Too much to explain here, do a bit of research. RE's are pretty much the same in php, mysql, Javascript, perl, python, and other implementations so it's really worth taking the time to learn.
A good book is "Mastering Regular Expressions":
http://www.oreilly.com/catalog/regex2/