Search code examples
phppreg-match

php preg match. Find elements with two values not in order


I got array like:

$array = array(
    3A32,
    4565,
    7890,
    0012,
    A324,
    9002,
    3200,
    345A,
    0436
);

Then I need to find which elements has two numbers. The value of number can change.

If values were:

$n1 = 0; 
$n2 = 3;

For that search preg_match() should return (3200,0436)

If values were:

$n1 = 0; 
$n2 = 0;

preg_match() should return (0012,3200,9002)

Any idea?

Thanks.


Solution

  • Instead of using preg_match, you might use preg_grep and dynamically create a pattern that will match the 2 values in each order using an alternation.

    ^[A-Z0-9]*0[A-Z0-9]*3[A-Z0-9]*|[A-Z0-9]*3[A-Z0-9]*0[A-Z0-9]*$
    

    The character class [A-Z0-9] matches either a char A-Z or a digit 0-9.

    Regex demo | Php demo

    If you want to use other characters, you could also take a look at preg_quote to handle regular expression characters.

    function getElementWithTwoValues($n1, $n2) {
        $pattern = "/^[A-Z0-9]*{$n1}[A-Z0-9]*{$n2}[A-Z0-9]*|[A-Z0-9]*{$n2}[A-Z0-9]*{$n1}[A-Z0-9]*$/";
        $array = array(
            "3A32",
            "4565",
            "7890",
            "0012",
            "A324",
            "9002",
            "3200",
            "345A",
            "0436"
        );
    
        return preg_grep($pattern, $array);
    }
    
    print_r(getElementWithTwoValues(0, 3));
    print_r(getElementWithTwoValues(0, 0));
    

    Output

    Array
    (
        [6] => 3200
        [8] => 0436
    )
    Array
    (
        [3] => 0012
        [5] => 9002
        [6] => 3200
    )