Clean link on search filter php - php

I have a function to clean a link when I filter my search results
function cleanLink($url,$remove){
$aQ = explode("&",str_replace("?", "", $url));
foreach ($aQ as $part) {
$pos = strpos($part, $remove);
if ($pos === false)
$queryClean[] = $part;
}
$line = implode("&", $queryClean);
return "?".$line;
}
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
This works fine, for example if my url is
www.mysite.com/?q=wordx
I want to add an "order alphabetic desc" so my url returns
www.mysite.com/?q=wordx&order=desc
but if my query string is empty (e.g. www.mysite.com/) the return is
www.mysite.com/?&q=word
How can I remove the & if the query string is empty?

Change
if ($pos === false)
to
if ($pos === false && $part)
to omit empty $part string (will evaluate as false). You also should initialize $queryClean
$queryClean = array();

You can use parse_str and http_build_str to remove a parameter from the query string. You just to make sure pecl_http >= 0.23.0 is installed
function cleanLink($queryString, $remove)
{
parse_str($queryString, $query);
if (array_key_exists($remove, $query)) {
unset($query[$remove]);
}
return http_build_str($query);
}
$linkACTUAL = $_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q");
echo $linkACTUAL . "&q=" . $word;
For more information see http://php.net/manual/en/function.http-build-str.php and http://php.net/manual/de/function.parse-str.php

If your function is running fine when there are query string then you can simply put your function call inside if statement like
if(!empty($_GET))
{
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
}
Updated:
echo (false === strpos($linkACTUAL, "&")) ? $linkACTUAL."q=".$word : $linkACTUAL."&q=".$word;

Related

Find Word Which comes first in php

I have 2 words like %sku% and %any% that will be used in the sites url structure.
This data will be saved in a database and I need to find out which comes first.
E.g.
In the below url %sku% comes first
http://example.com/%sku%/product/%any%
While in the below url %any% comes first
http://example.com/%any%/product/%sku%
Furthermore I cant be sure that the structure will be consistent it could be like any of the below:
http://example.com/%sku%/product/%any%
http://example.com/%any%/product/%sku%
http://example.com/%any%/%sku%
http://example.com/product/%sku%
http://example.com/product/%any%
I want to check which comes first and which comes last.. but %sku% and%any%` are defined by me.. so i can be 100% sure that those tags are going to be used.
The following code will return the first and last occurring items from a designated $attributes array.
$string = 'http://example.com/%sku%/product/%any%';
// values to check for
$attributes = ['%sku%', '%any%'];
$results = array();
foreach($attributes as $attribute)
{
// Get position of attribute in uri string
$pos = strpos($string, $attribute);
// if it exists we add it to the array with the position
if($pos)
{
$results[$attribute] = $pos;
}
}
// Get the first occuring attribute
$firstOccuringAttribute = array_search( min($results), $results);
// Get the last occuring attribute
$lastOccuringAttribute = array_search( max($results), $results);
This could be refactored into something a bit more readable:
$uri = 'http://example.com/%sku%/product/%any%';
$attributes = ['%sku%', '%any%'];
$lastAttribute = getLastAttribute($uri, $attributes);
$firstAttribute = getFirstAttribtue($uri, $attributes);
function getAttributeWeighting($uri, $attributes)
{
$results = array();
foreach($attributes as $attribute)
{
$pos = strpos($uri, $attribute);
if($pos)
{
$results[$attribute] = $pos;
}
}
return $results;
}
function getFirstAttribute($uri, $attributes)
{
$attributeWeighting = getAttributeWeighting($uri, $attributes);
return array_search( min($attributeWeighting), $attributeWeighting);
}
function getLastAttribute($uri, $attributes)
{
$attributeWeighting = getAttributeWeighting($uri, $attributes);
return array_search( max($attributeWeighting), $attributeWeighting);
}
Just use strpos
something like:
$URL = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$posOfSku=strlen($URL);
$posOfAny=strlen($URL);
if(strpos($URL ,'%sku%') !== false) {
$posOfSku = strpos($URL ,'%sku%');
}
if(strpos($URL ,'%any%') !== false) {
$posOfAny= strpos($URL ,'%any%');
}
$result = ($posOfAny < $posOfSku) ? 'any came 1st' : 'sku came 1st';
echo $result;

preg_replace remove parameter variable

Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}

get string piece, before last needle

Given
$str = "asd/fgh/jkl/123
If we want to get string piece after last slash , we can use function strrchr() right?
In php not function, to get string piece, before last slah, that is asd/fgh/jkl ?
I know this can make via regex or other way, I am asking about internal function?
You can use
$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));
Output
asd/fgh/jkl
$str = "asd/fgh/jkl/123";
$lastPiece = end(explode("/", $str));
echo $lastPiece;
output: 123;
explode() converts the string into an array using "/" as a separator (you can pick the separator)
end() returns the last item of the array
You can do this by:
explode — Split a string by string (Documentation)
$pieces = explode("/", $str );
example
$str = "asd/fgh/jkl/123";
$pieces = explode("/", $str );
print_r($pieces);
$count= count($pieces);
echo $pieces[$count-1]; //or
echo end($pieces);
Codepad
Use this powerful custom function
/* $position = false and $sub = false show result of before first occurance of $needle */
/* $position = true and $sub false show result of before last occurance of $needle */
/* $position = false and $sub = true show result of after first occurance of $needle */
/* $position = true and $sub true show result of after last occurance of $needle */
function CustomStrStr($str,$needle,$position = false,$sub = false)
{
$Isneedle = strpos($str,$needle);
if ($Isneedle === false)
return false;
$needlePos =0;
$return;
if ( $position === false )
$needlePos = strpos($str,$needle);
else
$needlePos = strrpos($str,$needle);
if ($sub === false)
$return = substr($str,0,$needlePos);
else
$return = substr($str,$needlePos+strlen($needle));
return $return;
}

PHP strpos not working

I've always had problems with strpos, I understand the num v. boolean issue, but I can NOT get this working. The $cur_key value is something like "page=>name"...
$pos = strpos($cur_key, "=>");
if ($pos !== false) {
$mod = explode("=>",$cur_key);
$path = $mod[0];
$param = $mod[1];
}else{
$path = $cur_key;
}
If it's in there it should split it into the two values but no matter what I try it's always just returning the original value...
$mod = explode('=>',$cur_key);
$path=$mod[0];
if (sizeof($mod)>1) $param=$mod[1]; else $param='';

Detect Dir after / in a URL

I want to write a PHP script which will first detect URL's and see if they have sub dir or not, if they are simple URL like site.com then it would write 1 in one of the DB's table but if the URL is something like this site.com/images or site.com/images/files then it should'nt do the query..
EDIT: Answer by Mob it works but doesnt work if there are more than one url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
Use parse_url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
EDIT:
To parse multiple urls;
Store the urls in an array.
Use a loop to iterate over the array while passing the values to a function that performs the check
Here:
<?php
$arr = array("http://google.com",
"http://google.com/image/",
"http://flickr.com",
"http://flickr.com/image" );
foreach ($arr as $val){
echo $val." ". check($val)."\n";
}
function check ($url){
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
return "true";
} else {
return "false";
}
}
?>
The output is :
http://google.com false
http://google.com/image/ true
http://flickr.com false
http://flickr.com/image true
Try strpos()
Syntax: strpos($haystack, $needle)
You could use something like:
if (!strpos($url, '/'))
{
do_query();
}
edit
Remember to strip the slashes in http://, of course.
$_SERVER is what you need. I'll let you google it.

Categories