Replace url paramer by using php - php

I have a url & its structure like
https://www.example.com/i/location-name/category/subcategory/item/item-id
I want to replace the url parameter(location-name) dynamically by new parameter using PHP.
Modified url is looks like this
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
I had successfully done with query parameters by using http_build_query();
But in this case i had tried with preg_replace(), but its not working
Thanks

If you would like to use regex.
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
print preg_replace('|/location-name/|','/'.$new_param.'/',$url);
I don't recommend search for only location-name (without slash) beacause it will match with for example location-names string.
UPDATE
Based on placement not string you can change that part that way:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
$new_param = 'another-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
You will get:
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
https://www.example.com/i/another-parameter/category/subcategory/item/item-id
Alternative solution
If you would like to be sure about change, you can do it another way, something like this:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-param';
$parts = parse_url($url);
$path_parts = explode('/',$parts['path']);
$path_parts[2] = $new_param;
$new_path = implode('/',$path_parts);
$new_url = $parts['scheme'].'://'.$parts['host'].$new_path;
print( $new_url);

Try this one:
$new_url = str_replace('location-name', 'my-location', 'https://www.example.com/i/location-name/category/subcategory/item/item-id')

Related

PHP parameters inside url cumulated parameter

lets say I have an url
http://www.somepage.com/clicker.php?id_campaign=8&id_email=9324&url=https://www.google.com/search?q=dog&sxsrf=ALeKk019eteEpAwVf2Fk4qYo7TiwhuMQ_Q:1596666153666&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiqzqf3jIXrAhUisaQKHRayBWAQ_AUoAXoECBkQAw&biw=1920&bih=921#imgrc=M4wsJO0A7OQfTM
and im trying to get out the parameters id_campaign, id_email and url
however, using the code:
$url = htmlspecialchars_decode($url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
when printing $parts['query'] it only gives me:
https://www.google.com/search?q=dog
because rest of the url it consider as another parameter...
so how do I get all the url parameter out of $url?
In an ideal scenario, the URLs passed within the query would be URL-encoded, as opposed to HTML-encoded.
What you could do in your case is manually replace all & by something temporary and then replace them all back after parsing the URL. This is not exactly pretty, but works:
$url = str_replace('&', '__TEMP__', $url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
$urlParam = str_replace('__TEMP__', '&', $query['url']);
echo $urlParam;
Demo

Changing specific text in php

$url = localhost/project/index.php?letter=0&position=0&bypass=1
How to change position=0 to position=1?
The new $url value will be:
$url = localhost/project/index.php?letter=0&position=1&bypass=1
You can use parse-str and parse-url approach with the help of http-build-query,
$url = "localhost/project/index.php?letter=0&position=0&bypass=1";
// fetching query paramters and save it to output variable
parse_str(parse_url($url,PHP_URL_QUERY),$output);
// changing position value
$output["position"] = 1;
// building back query string
$query = http_build_query($output);
// creating final string
echo parse_url($url,PHP_URL_PATH)."?".$query;
Demo
Output:-
localhost/project/index.php?letter=0&position=1&bypass=1
You have to use the str_replace() function to replace a specific text from string.
$url = str_replace('position=0','position=1',$url);

PHP Parse URL From Current URL

I am trying to parse url and extract value from it .My url value is www.mysite.com/register/?referredby=admin. I want to get value admin from this url. For this, I have written following code. Its giving me value referredby=admin, but I want only admin as value. How Can I achieve this? Below is my code:
<?php
$url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
setcookie('ref_by', parse_url($url, PHP_URL_QUERY));
echo $_COOKIE['ref_by'];
?>
You can use parse_str() function.
$url = "www.mysite.com/register/?email=admin";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
Try this code,
$url = "www.mysite.com/register/?referredby=admin";
$parse = parse_url($url, PHP_URL_QUERY);
parse_str($parse, $output);
echo $output['referredby'];
$referred = $_GET['referredby'];
$referred = "referredby=admin";
$pieces = explode("=", $referred);
echo $pieces[1]; // admin
I don't know if it's still relevant for you, but maybe it is for others: I've recently released a composer package for parsing urls (https://www.crwlr.software/packages/url). Using that library you can do it like this:
$url = 'https://www.example.com/register/?referredby=admin';
$query = Crwlr\Url\Url::parse($url)->queryArray();
echo $query['referredby'];
The parse method parses the url and returns an object, the queryArray method returns the url query as array.
Is not a really clean solution, but you can try something like:
$url = "MYURL";
$parse = parse_url($url);
parse_str($parse['query']);
echo $referredby; // same name of the get param (see parse_str doc)
PHP.net: Warning
Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.
Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.
Read section on security of Using Register Globals explaining why it is dangerous.

PHP: str_replace within a word/phrase

I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.
Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90
This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;
$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);

preg_match - extracting string from url

I've got an URL's like this:
http://localhost/adminator/index.php?section=1portal&tool=2firmy
and
http://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26
and I want to be able to extract the SECTION and TOOL parameters.
I've came up with this:
preg_match('/(.*)(section=)(.*)(&tool=)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];
But this works only for the first URL, not the second, and than I have this:
preg_match('/(.*)(section=)(.*)(&tool=)(.*)(&)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];
And this only works for the second url, not the first.
How can I make it work in both cases? Thanks.
$url = 'http://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26';
$url = parse_url($url, PHP_URL_QUERY);
parse_str($url, $output);
echo $output['section']; // 1portal
echo $output['tool']; // 2firmy
Can't you just use $_GET['section'] and $_GET['tool']?
'section=(.+?).*?&tool=(.+?)' should work, then check group 1 and 2 for the value

Categories