Bing Lin
Bing Lin

Reputation: 97

Filtering repeated phone numbers in PHP

The output has repeated results/rows - something is wrong with the filtering.

While cycling to read the SQL results the output has to meet these conditions:

Condition 1: The message contains no emails: /[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i

Condition 2: The message must contain a Portuguese mobile number, 9 digits, starting with 91, 92, 93 or 96, and it can have space between each group of 3 numbers: /(9[1236][0-9]) ?([0-9]{3}) ?([0-9]{3})/

910 000 000 and 920123123 are valid matches.

Condition 3: The preg_match result (phone number) must not repeat, my intention is that if someone has 2 or 3 posts with same phone number, just output the first one only.

If the 9 digit phone number already exits this cycle, output the first, skip the rest, go back to while cycle.

$array = array();

while ($result = $query->fetch_array()) {
    $temp = array();
    if (preg_match('/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i', $result['message']) == false) {
        if (preg_match('/(9[1236][0-9]) ?([0-9]{3}) ?([0-9]{3})/', $result['message'], $temp)) {
            preg_replace(" ", "", $temp);
            foreach($temp as $value) {
                if ((array_search($value, $array) == false) && (strlen($value) == 9)) {
                    array_push($array, $value);
                    /*HTML OUTPUTS HERE*/
                }
            }
        }
    }
}

Upvotes: 1

Views: 155

Answers (2)

dchesterton
dchesterton

Reputation: 2110

$array = array();
while ($result = $query->fetch_array()) {
    $temp = array();
    if (preg_match('/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i', $result['message']) == false) {
        if (preg_match('/(9[1236][0-9]) ?([0-9]{3}) ?([0-9]{3})/', $result['message'], $temp)) {
            $phone = str_replace(' ', '', $temp[0]);

            if (array_search($phone, $array) === false) {
                $array[] = $phone;
            }
        }
    }
}

Some notes:

  • str_replace is faster than preg_replace for simple, non-regular expression replacements.
  • array_search can return 0 when the value is in the first element of the array, so you need to use the === operator.
  • Lastly, there's no need for the last foreach loop as the full phone number is the first element in $temp.

Upvotes: 1

user679846
user679846

Reputation:

In your query, I think it's best to indicate DISTINCT for removal of repeated results.

e.g:

SELECT DISTINCT(*) FROM table_name WHERE 1;

Upvotes: 0

Related Questions