tags:

views:

28

answers:

2

how do i use preg_match for partial matches?

when i have the term

www.stackoverflow.com

and when i enter

stackoverflow.com or stackoverflow

to match the phrase it returns false. How do i make it work for partial matches?

A: 

preg_match is not anchored by default so it will find partial matches without any special effort. Do you have the arguments in the correct order? It's the regex first, then the string to be searched. So:

if (preg_match('/stackoverflow/', 'www.stackoverflow.com')) {
    ...
}
John Kugelman
+1  A: 

preg_match uses regular expressions, which you can get a very good tutorial for here.

In your specific case, you are looking for a string, followed by an optional segment (to change your search into English, you want to find "stackoverflow", optionally followed by ".com"). Sections of regular expressions can be made optional by using the ? modifier:

preg_match('/stackoverflow(\.com)?/', $your_string)

The regular expression here (/stackoverflow(\.com)?/) says the same thing as our English version above -- match "stackoverflow" followed by an optional ".com".

Here's a quick overview of how the regex works:

  • The slash on each end of the pattern is a delimiter which PHP uses to enclose regular expressions.
  • The majority of characters in regular expressions are matched literally, so stackoverflow matches "stackoverflow"
  • The parentheses define a group, which is made optional by the ?. Without the group, only the token directly before the ? would be made optional (in this case the "m").
  • Note that there is a slash before the dot in ".com". This is because dots are special characters in regular expressions (used kind of like a wildcard), so it needs to be escaped if you want to match a literal dot.
Daniel Vandersluis