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']);
Related
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
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 !
I have to extract a string like this:
index.php?module=Reports&action=abc&rname=Instantpayment
Now my task is to extract report, action and rname value in PHP.
I have tried by using explode(), but I am not able to extract module.
How can I do it?
You could use parse_str() in this case:
$string = 'index.php?module=Reports&action=abc&rname=Instantpayment';
$string = substr($string, strpos($string, '?')+1); // get the string from after the question mark until end of string
parse_str($string, $data); // use this function, stress free
echo '<pre>';
print_r($data);
Should output:
Array
(
[module] => Reports
[action] => abc
[rname] => Instantpayment
)
$yourUrl="module=Reports&action=abc&rname=Instantpayment"
$exploded_array = array();
parse_str($yourUrl, $exploded_array);
$exploded_array['module'];
$exploded_array['action'];
$exploded_array['rname'];
Use $_GET to get query strings from the URL
echo $_GET['module']; //Reports
echo $_GET['action']; // abc
echo $_GET['rname']; // Instantpayment
For getting from the string try explode():
$str ='index.php?module=Reports&action=abc&rname=Instantpayment';
$e = explode('?', $str);
$e1 = explode('&', $e[1]);
foreach($e1 as $v) {
$ex = explode('=', $v);
$newarr[$ex[0]] = $ex[1];
}
print_r($newarr); // Use this array of values you want.
//Array ( [module] => Reports [action] => abc [rname] => Instantpayment )
echo $newarr['module'];
echo $newarr['action'];
echo $newarr['rname'];
You have to access the globale GET variable:
$_GET['module']
$_GET['action']
$_GET['rname']
Try this:
<?php
$temp = "index.php?module=Reports&action=abc&rname=Instantpayment";
$t1 = explode("=",$temp);
for ($i = 1; $i < sizeof($t1); $i++)
{
$temp = explode("&", $t1[$i]);
echo $temp[0] . "\n";
}
?>
I generate an array with URL's from a webpage with file_get_contents, that i want to remove entry's (key & value) from if they contain specific data.
For example:
[0] = 'http://somesite.com'
[1] = 'http://someothersite.com/article/id/55/file.pdf'
[2] = 'http://someothersite.com/article/id/56/file2.pdf'
[3] = 'javascript:void(0)'
[4] = 'mailto:info#somesite.com'
I want to remove the entry's
http://somesite.com
javascript:void(0)
mailto:info#somesite.com
Because i only need the URL's with the .pdf files.
How do i do that?
You can use array filter for this (note this syntax works for php 5.3+)
$filtered = array_filter($array, function ($a){ return preg_match ('/.pdf$/', $a); });
Hopefully this will help:
$sites[0] = 'http://somesite.com';
$sites[1] = 'http://someothersite.com/article/id/55/file.pdf';
$sites[2] = 'http://someothersite.com/article/id/56/file2.pdf';
$sites[3] = 'javascript:void(0)';
$sites[4] = 'mailto:info#somesite.com';
echo '<pre>'.print_r($sites, true).'</pre>';
//loop through your array of items/sites
foreach($sites as $key=>$value){
//remove whitespace
$value = trim($value);
//get last 4 chars of value
$ext = substr($value, -4, 0);
//check if it is not .pdf
if($ext != '.pdf'){
//unset item from array
unset($sites[$key]);
}
}
echo '<pre>'.print_r($sites, true).'</pre>';
$array = array('http://somesite.com','http://someothersite.com/article/id/55/file.pdf','http://someothersite.com/article/id/56/file2.pdf','javascript:void(0)','mailto:info#somesite.com');
for($i=0; $i<=count($array)+1 ; $i++)
{
if(end(explode('.',$array[$i])) != "pdf" )
{
unset($array[$i]);
}
}
Try this !!!!
$haystack = array (
'0' => 'http://somesite.com',
'1' => 'http://someothersite.com/article/id/55/file.pdf',
'2' => 'http://someothersite.com/article/id/56/file2.pdf',
'3' => 'javascript:void(0)',
'4' => 'mailto:info#somesite.com'
);
$matches = preg_grep ('/pdf/i', $haystack);
//print_r ($matches);
foreach($matches as $k=>$v):
echo $matches[$k]."<br/>";
endforeach;
Documentation
preg_grep
array_filter is always an option, but if you want to remove specific values another good candidate is array_diff:
$remove = [
'http://somesite.com',
'javascript:void(0)',
'mailto:info#somesite.com',
];
$filtered = array_diff($array, $remove);
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=.