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?
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?
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')) {
...
}
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:
stackoverflow
matches "stackoverflow"?
. Without the group, only the token directly before the ?
would be made optional (in this case the "m").