D
D
Dima2018-04-10 14:21:05
PHP
Dima, 2018-04-10 14:21:05

How to find a number in an array using a pattern?

Let's say we have an array with numbers:

$array = ['9096223434', '9096660865', '9096225151'];

How to extract from it the numbers that match the pattern XYXY (given that X and Y are unknown)? In the current case, we can get the numbers 909622 3434 and 909622 5151 .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eternalfire, 2018-04-10
@avbrugen

<?php
$mask = 'abab';

$rgPattern = array(
    'aaaa'   => '/(\d)\1{3}/',
    'aabb'   => array(
        '/(\d)\1(?!\1)([^\1])\2/',
        '/(\d)\1([^\1])\2([^\1\2])\3/'
    ),
    'abab'   => array(
        '/(\d)([^\1])(?:\1(?!\1)\2){1}/',
        '/(\d)([^\1])\1\2\1\2/'
    ),
    'aabbcc' => '/(\d)\1([^\1])\2([^\1\2])\3/',
    'ababab' => '/(\d)([^\1])\1\2\1\2/',
    'abcabc' => '/(\d)([^\1])([^\1\2])\1\2\3/'
);

$rgNum = array(9096223434, 9096660865, 9096225151);

$pattern = $rgPattern[$mask];

$result = array_filter($rgNum, function($num) use ($pattern) {
   
    $num = preg_replace('/\D/', '', $num);
   
    if(is_array($pattern)) {
        return (preg_match($pattern[0], $num) && !preg_match($pattern[1], $num));    
    }
   
    return !!preg_match($pattern, $num);
});

print_r($result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question