user3436467
user3436467

Reputation: 1775

comparing two strings, one string has a wildcard

I have two strings which I would like to compare.

string1 = www.domain.com

string2 = *.domain.com

Normally, if we use if ($string1 == $string2).. these shouldn't match as they are not equal, however, since string2 is a wildcard, I would like it to be a match.

Condition(s)

  1. *.domain.com should match with ***anything**.domain.com*
  2. *.domain.com should be a mismatch for *domain.com* or *something.adifferent.com*
  3. need a solution to support all TLD's i.e. .com, .net, .org. .com.au etc..

How can I achieve this?

Upvotes: 3

Views: 696

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

I am not sure about 2 point that you tell in your question, but i think you need do like this:-

<?php


$string1 = '*.domain.com';

$string2 = 'www.domains.com';

$pattern = 'domain'; // put any pattern that you want to macth in both the string.

    if(preg_match("~\b$pattern\b~",$string1) && preg_match("~\b$pattern\b~",$string2) && substr_count($string1,'.') == substr_count($string2,'.')){
        echo 'matched';
    }else{
        echo 'not matched';
    }

?>

Output:- http://prntscr.com/7alzr0

and if string2 converted to www.domain.com then

http://prntscr.com/7am03m

Note:- 1. if you want the below will match also then go for the given condition.

example:--
$string1 = '*.domain.com'; 
$string2 = 'abc.login.domain.com'; 

if(preg_match("~\b$pattern\b~",$string1) && preg_match("~\b$pattern\b~",$string2) && substr_count($string1,'.') <= substr_count($string2,'.')){ 

Upvotes: 1

Related Questions