Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two strings, one string has a wildcard

Tags:

php

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?

like image 812
user3436467 Avatar asked Dec 22 '25 08:12

user3436467


1 Answers

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,'.')){ 
like image 196
Anant Kumar Singh Avatar answered Dec 23 '25 22:12

Anant Kumar Singh