0

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 :)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

regexr link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.