PHP Filter Array for double Elements -
i've got question. got array filled external links like:
www.google.de www.google.com/test
and on. no array filltered. if there links in array this:
www.google.de www.google.de/test www.google.de/fuuuu
i want www.google.de link , filter rest out of it. startet use array_diff_key not working should. here snippet.
$d_array = array_diff_key($externalarray, array_unique($externalarray));
thanks help. greats, traxstar
finally, did :
$arr = [ 'www.google.de', 'http://www.google.de/test', 'www.google.de/fufufufu', 'www.google.com/cctvvmb', 'https://www.google.com/', 'google.co.uk/hello', ]; // based on http://stackoverflow.com/questions/1201194/php-getting-domain-name-from-subdomain function get_domain($url) { if(preg_match('/(?p<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $url, $regs)) { return $regs['domain']; } return false; } function get_duplicated_domains($arr) { $domains = []; // looping array, processing of foreach($arr $url) { // lower text $url = strtolower($url); // removing eventual http & https $url = str_replace('http://', '', $url); $url = str_replace('https://', '', $url); // replacing string before first slash $url = explode('/', $url); // extracting top level domain $url = get_domain($url[0]); // registering domain in $domains array or incrementing if(array_key_exists($url, $domains)) { $domains[$url]++; } else { $domains[$url] = 0; } } // gathering data return array_keys(array_filter($domains)); } $res = get_duplicated_domains($arr);
result :
array ( [0] => google.de [1] => google.com )
what script doing ?
1 - looping array
1.1 - lowering url string prevent
http
mismatchhttp
exemple1.2 - removing
http://
&https://
strings, make same format1.3 - extracting top level domain name
1.4 - registering or incrementing
$domains
array on extracted top level domain name
2 - filtering array (0, null, false, empty strings, removed, that's why register domain name 0 , not 1) keep 'doubt' domains (the ones present more 1 time in array)
3 - getting keys of array (because keys domain names)
btw i'm running php 5.6.2
Comments
Post a Comment