Aadi
Aadi

Reputation: 7109

How to get pattern matching in php array using RegEx

I have following set of an array

array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');

and I would like to get all element which matching following patterns,

$matchArray  = array('*.example.com/*','www.demo.com');

Expected result as

array('www.example.com/','www.demo.example.com/','www.example.com/blog','www.demo.com');

Thanks :)

Upvotes: 0

Views: 5020

Answers (2)

Ingmar Boddington
Ingmar Boddington

Reputation: 3500

This works:

    $valuesArray = array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');
    $matchArray  = array('*.example.com/*','www.demo.com');
    $matchesArray = array();

    foreach ($valuesArray as $value) {
        foreach ($matchArray as $match) {

            //These fix the pseudo regex match array values
            $match = preg_quote($match);
            $match = str_replace('\*', '.*', $match);
            $match = str_replace('/', '\/', $match);

            //Match and add to $matchesArray if not already found
            if (preg_match('/'.$match.'/', $value)) {
                if (!in_array($value, $matchesArray)) {
                    $matchesArray[] = $value;
                }
            }

        }
    }

    print_r($matchesArray);

But I would reccomend changing the syntax of your matches array to be actual regex patterns so that the fix section of code is not required.

Upvotes: 1

Scott Weaver
Scott Weaver

Reputation: 7361

/\w+(\.demo)?\.example\.com\/\w*|www\.demo\.com/

regexr link

Upvotes: 0

Related Questions