Compare host name from array of URLs and get unique values - php

I need to compare URLs and remove duplicates from array but I want compare only host from url. I need skip http and https and www and others like last slash when I compare.
So when I have array:
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
Result will be only
http://www.google.com/test
http://www.google.com/example
http://www.facebook.com/example
I tried to compare like :
$urls = array_udiff($urls, $urls, function ($a, $b) {
return strcmp(preg_replace('|^https?://(www\\.)?|', '', rtrim($a,'/')), preg_replace('|^https?://(www\\.)?|', '', rtrim($b,'/')));
});
But it return me empty array.

<?php
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
$MyArray = [];
for($i=0;$i<count($urls);$i++) {
preg_match_all('/www.(.*)/', $urls[$i], $matches);
if (!in_array($matches[1], $MyArray))
$MyArray[] = $matches[1];
}
echo "<pre>";
print_r($MyArray);
echo "</pre>";
And the output is
Array
(
[0] => Array
(
[0] => google.com/test
)
[1] => Array
(
[0] => google.com/example
)
[2] => Array
(
[0] => facebook.com/example
)
)
trimmed and keeping only the host name

Try this approach :
<?php
function parseURLs(array $urls){
$rs = [];
foreach($urls as $url){
$segments = parse_url($url);
if(!in_array($segments['host'], $rs))
$rs[] = $segments['host'];
}
return $rs;
}
Then :
<?php
$urls = array(
'http://www.google.com',
'https://www.google.com',
'https://www.google.com/',
'https://www.facebook.com',
'http://www.facebook.com'
);
$uniqueURLs = parseURLs($urls);
print_r($uniqueURLs);
/* result :
Array
(
[0] => www.google.com
[1] => www.facebook.com
)
*/

You need to Loop through the URL's, Parse URL with PHP's url_parse() function and use array_unique to remove duplicates from array, so we are checking both the host and path ..
I have written a class for you:
<?php
/** Get Unique Values from array Values **/
Class Parser {
//Url Parser Function
public function arrayValuesUrlParser($urls) {
//Create Container
$parsed = [];
//Loop Through the Urls
foreach($urls as $url) {
$parse = parse_url($url);
$parsed[] = $parse["host"].$parse["path"];
//Delete Duplicates
$result = array_unique($parsed);
}
//Dump result
print_r($result);
}
}
?>
Using the Class
<?php
//Inlcude tghe Parser
include_once "Parser.php";
$urls = array(
'http://www.google.com/test',
'https://www.google.com/test',
'https://www.google.com/example',
'https://www.facebook.com/example',
'http://www.facebook.com/example');
//Instantiate
$parse = new Parser();
$parse->arrayValuesUrlParser($urls);
?>
You can do it in one file if you don't need to seperate files but you will have to remove include_once if you are using one php file. This class is also on PHP Classes, did it for fun !
Best of Luck !

Related

PHP array filter by pre text from value

I have an array like below
Array
(
[0] => country-indonesia
[1] => country-myanmar
[2] => access-is_airport
[3] => heritage-is_seagypsy
)
From that array I want to make separate array only for [country] ,[access], [heritage]
So for that I have to check array value by text before '-'. I am not sure how to do it. so i can't apply code here. I just have the array in PHP
A modified answer, if you want to get the specific types only.
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
$types = ['country', 'heritage', 'access'];
foreach ($arr as $element) {
$fac = explode('-', $element);
foreach ($types as $type) {
if ($fac[0] === $type) {
$new_array[$type][] = $fac[1];
}
}
}
$country = $new_array['country'];
$access = $new_array['access'];
$heritage = $new_array['heritage'];
var_dump($new_array);
A simple and easy solution in 3 lines of code using array_walk
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
//if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
$new_array[$key][] = $value;
});
print_r($new_array);
Gives this output:
Array
(
[country] => Array
(
[0] => indonesia
[1] => myanmar
)
[access] => Array
(
[0] => is_airport
)
[heritage] => Array
(
[0] => is_seagypsy
)
)
If you don't want empty and duplicate entries:
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
if(empty($value) || array_key_exists($key, $new_array) && in_array($value, $new_array[$key])) return;
$new_array[$key][] = $value;
});
print_r($new_array);
you can do it by using explode and in_array functions
<?php
$arr = ["country-indonesia","country-myanmar","access-is_airport","heritage-is_seagypsy"];
$newArr = array();
foreach($arr as $k=> $val){
$valArr = explode("-", $val);
if(!in_array($valArr[0], $newArr)){
$newArr[] = $valArr[0];
}
}
print_r($newArr);
?>
live demo
You need PHP's strpos() function.
Just loop through every element of the array and try something like:
if( strpos($array[$i], "heritage") != false )
{
// Found heritage, do something with it
}
(Rough example written from my cellphone while feeding baby, may have typos but it's the basics of what you need)
Read further here: http://php.net/manual/en/function.strpos.php
//first lets set a variable equal to our array for ease in working with i.e
// also create a new empty array to hold our filtered values
$countryArray = array();
$accessArray = array();
$heritageArray = array();
$oldArray = Array(country-indonesia, country-myanmar, access-is_airport, heritage-is_seagypsy);
//Next loop through our array i.e
for($x = 0; $x < count($oldArray); $x++){
// now filter through the array contents
$currentValue = $oldArray[$x];
// check whether the current index has any of the strings in it [country] ,[access], [heritage] using the method : strpos()
if(strpos($currentValue,'country')){
//if this particular value contains the keyword push it into our new country array //using the array_push() function.
array_push($countryArray,$currentValue);
}elseif(strpos($currentValue,'access')){
// else check for the access string in our current value
// once it's found the current value will be pushed to the $accessArray
array_push($accessArray,$currentValue);
}elseif(strpos($currentValue,'heritage')){
// check for the last string value i.e access. If found this too should be pushed to //the new heritage array i.e
array_push($heritageArray,$currentValue);
}else{
// do nothing
}
}
//I believe that should work: cheers hope

PHP return second value of 2D array

I have the following PHP code:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".
I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.
Any help would be appreciated
You can use something like this:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));
$output = $special_files[$key][1]; //outputs "Trump"
Here is a working sample.
Well, you can try the following:
foreach ($special_files as $special_file) {
$i = 1;
foreach ($special_file as $element) {
if ($i==2) {
echo ("Second value is: " . $element);
break;
}
$i++;
}
}
You can extract the [1] elements and index them by the [0] elements:
$lookup = array_column($special_files, 1, 0);
$result = isset($lookup['Donald']) ?: false;
The $lookup array yields:
Array
(
[Turnip] => Tweed
[Donald] => Trump
)

Want to Filter an array according to value

I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605

Rewrite dynamic substring in URL

As the title suggests, my goal is to add a rewrite statement in .htaccess to replace a dynamic substring in the middle of a URL. Additionally, I need all occurrences of "|" to be changed to "+".
For instance, I'd like to take this URL
www.domain.com/?t=p&c=some+string&skus=string1|string2|string3
And redirect it to:
www.domain.com/?q=string1+string2+string3
Basically, the substring to replace starts at "t=" and ends at "skus".
Is this possible? Is this easier to do with PHP?
You can use the parse_url function
this would do the trick
$url = "www.domain.com/?t=p&c=some+string&skus=string1|string2|string3";
echo "<pre>";
print_r($decoded = parse_url($url));
print_r($parsed = queryToArray($decoded['query']));
$parms = explode("|", $parsed['skus']);
print_r($parms);
echo "</pre>";
function queryToArray($qry)
{
$result = array();
//string must contain at least one = and cannot be in first position
if(strpos($qry,'=')) {
if(strpos($qry,'?')!==false) {
$q = parse_url($qry);
$qry = $q['query'];
}
}else {
return false;
}
foreach (explode('&', $qry) as $couple) {
list ($key, $val) = explode('=', $couple);
$result[$key] = $val;
}
return empty($result) ? false : $result;
}
the result should look like this
Array
(
[path] => www.domain.com/
[query] => t=p&c=some+string&skus=string1|string2|string3
)
Array
(
[t] => p
[c] => some+string
[skus] => string1|string2|string3
)
Array
(
[0] => string1
[1] => string2
[2] => string3
)
Use PHP built-in function when possible. So in this case use parse_url and parse_str.
$parts = parse_url($url);
parse_str($parts['query'], $query);
$params = explode('|', $query['skus']);

Get part of a dynamic url

I'm trying to get a part of the URL on my website
In this situation:
http://mywebsite/filexx/yyyyy/abaete/374
$url2 = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(preg_match("/\/(\d+)$/",$url2,$matches))
{
$meuid = $matches[1];
}
its works, but lets put 2 different situations:
http://mywebsite/filexx/yyyyy/abaete/374/?p=1
// i'm try to get the 374 (ID)
http://mywebsite/filexx/yyyyy/374/?p=1
// here the same
so I want to get last part if integer ( 374 )
or the part before the query 374/?p=1. So I want the 374.
Thanks.
I'll just make my comment an answer:
<?php
$string = 'http://mywebsite/filexx/yyyyy/abaete/374/?g=123';
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
?>
It will also ignore the /?getval1=1&getval2=2&etc=etc
Output
Array
(
[0] => Array
(
[0] => http://mywebsite/filexx/yyyyy/abaete/374/
)
[1] => Array
(
[0] => 374
)
)
$url = 'http://mywebsite/filexx/yyyyy/abaete/374/?p=1';
$explodedUrl = explode('/',$url);
$countArray = count($explodedUrl);
if(strpos($explodedUrl[$countArray-1],'?') === FALSE){
$yourId = $explodedUrl[$countArray-1];
} else {
$yourId = $explodedUrl[$countArray-2];
}
$yourId contains your Id
http://mywebsite/filexx/yyyyy/abaete/374
$url2 = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(preg_match('~([0-9]+)\/\?p=~', $url2, $matches))
{
$meuid = $matches[1];
}
This gets the numbers before /?p=.

Categories